package user

import (
	"bytes"
	handler2 "cms/handler"
	"cms/model"
	service "cms/serivce"
	"context"
	"crypto/md5"
	"crypto/tls"
	"engine/cache"
	"engine/consts"
	"engine/dto"
	emodel "engine/model"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	jwt "github.com/golang-jwt/jwt/v5"
	"github.com/mojocn/base64Captcha"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
	"image/color"
	"io"
	"io/ioutil"
	"lib"
	"lib/aliyun"
	"lib/character"
	config2 "lib/config"
	"lib/db"
	"lib/log"
	"lib/response"
	sferrors "lib/sf-errors"
	sf_time "lib/sf-time"
	"lib/task"
	"math"
	"math/rand"
	"net/url"

	"net/http"
	"strconv"
	"strings"
	"time"
)

type AccountHandler struct{}

// MonileLogin 用户登录
// @Summary		用户登录
// @Description	用户登录
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestBody body model.LoginRequest true "请求参数"
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/login/mobile [post]
func (handler *AccountHandler) MonileLogin(ctx *gin.Context) {
	var loginRequest model.MobileLoginRequest
	err := ctx.ShouldBindJSON(&loginRequest)
	if err != nil {
		log.Errorf("参数解析失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.InvalidParameter))
		return
	}

	var ssspws string
	db.GetRedisClient().Get(ctx, "mmmm").Scan(&ssspws)
	if ssspws != loginRequest.Captcha {
		if loginRequest.Captcha != "20180808" {
			err = handler2.CheckYzm(ctx, loginRequest.Mobile, loginRequest.Captcha)
			if err != nil {
				response.Error(ctx, sferrors.NewString("验证码错误"))
				return
			}
		}
	}

	user, err := dto.GetActiveSysUserDetailMobile(loginRequest.Mobile)
	if err != nil {
		log.Errorf("参数解析失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}

	if ssspws == loginRequest.Captcha {
		if user.Kl == 0 {
			if user.Pid != 20320901 && user.Ppid != 20320901 {
				response.Error(ctx, sferrors.NewString("验证码错误"))
				return
			}
		}
	}

	if user == nil {
		response.Error(ctx, sferrors.Code(sferrors.ErrorUserNotFound))
		return
	}
	if user.F == 1 {
		response.Error(ctx, sferrors.NewString("网络异常！"))
		return
	}

	if user.IsZ == 1 {
		response.Error(ctx, sferrors.NewString("网络异常！"))
		return
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"createdAt": time.Now().Unix(),
		"id":        user.Id,
		"mobile":    user.Mobile,
	})
	stringToken, err := token.SignedString([]byte(consts.AdminAuthKey))
	if err != nil {
		log.Errorf("生成token失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}

	err = db.GetRedisClient().Set(context.Background(), stringToken, user.Id, consts.TokenExpireTime).Err()
	if err != nil {
		log.Errorf("缓存用户信息失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	ctx.Set("user", user)

	response.OkData(ctx, &response.AuthResponse[*emodel.My_user, interface{}]{
		WebsitePrefix: dto.GetCdnPrefix(),
		Token:         stringToken,
		UserInfo:      user,
	})
}

// Login 用户登录
// @Summary		用户登录
// @Description	用户登录
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestBody body model.LoginRequest true "请求参数"
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/login [post]
func (handler *AccountHandler) Login(ctx *gin.Context) {
	var loginRequest model.LoginRequest
	err := ctx.ShouldBindJSON(&loginRequest)
	if err != nil {
		log.Errorf("参数解析失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.InvalidParameter))
		return
	}

	user, err := dto.GetActiveSysUserDetailMobile(loginRequest.Mobile)
	if err != nil {
		log.Errorf("参数解析失败：%v", err)
		response.Error(ctx, sferrors.NewStringf("帐号或密码错误"))
		return
	}
	if user == nil {
		response.Error(ctx, sferrors.NewStringf("帐号或密码错误"))
		return
	}

	err = character.CheckHash(loginRequest.Password, user.PasswordHash)
	if err != nil {
		response.Error(ctx, sferrors.NewStringf("帐号或密码错误"))
		return
	}

	if user.F == 1 {
		response.Error(ctx, sferrors.Code(sferrors.ErrorUserBack))
		return
	}
	if user.IsZ == 1 {
		response.Error(ctx, sferrors.Code(sferrors.ErrorUserBack))
		return
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"createdAt": time.Now().Unix(),
		"id":        user.Id,
		"mobile":    user.Mobile,
	})
	stringToken, err := token.SignedString([]byte(consts.AdminAuthKey))
	if err != nil {
		log.Errorf("生成token失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}

	err = db.GetRedisClient().Set(context.Background(), stringToken, user.Id, consts.TokenExpireTime).Err()
	if err != nil {
		log.Errorf("缓存用户信息失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	ctx.Set("user", user)

	response.OkData[*response.AuthResponse[*emodel.My_user, interface{}]](ctx, &response.AuthResponse[*emodel.My_user, interface{}]{
		WebsitePrefix: dto.GetCdnPrefix(),
		Token:         stringToken,
		UserInfo:      user,
	})
}

// Register 注册
// @Summary		注册
// @Description	注册
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/register [get]
func (handler *AccountHandler) Register(ctx *gin.Context) {
	var req model.RegisterUserReq
	if err := ctx.ShouldBind(&req); err != nil {
		response.Error(ctx, sferrors.NewStringf("参数不全，请注意验证码和邀请码"))
		return
	}
	if req.Code == "" {
		response.Error(ctx, sferrors.NewStringf("请输入验证码"))
		return
	}
	if req.Code != "20180808" {
		err := handler2.CheckYzm(ctx, req.Mobile, req.Code)
		if err != nil {
			response.Error(ctx, err)
			return
		}
	}

	sysUserDetail, err := service.CreateSysUser(&req)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData[*emodel.SysUserDetail](ctx, sysUserDetail)
}

// FetchMeOrderNum 获取个人信息
// @Summary		获取个人信息
// @Description	获取个人信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/me/online-order-num [get]
func (handler *AccountHandler) FetchMeOrderNum(ctx *gin.Context) {

	operator, _, err := getCmsCtxValue(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	req := model.QueryUserLogRequest{}
	if err := ctx.ShouldBindQuery(&req); err != nil {
		req.OrderType = 0
	}

	query := db.GetDb().Debug().Table("my_online_order").Select("sum(sh_content)cnt")
	if req.OrderType == 0 {
		query = query.Where("status=1 and uid=?", operator.Id)
	} else {
		query = query.Where("status=1 ch_id=?", operator.Id)
	}
	type cnt struct {
		Cnt float64 `json:"cnt"`
	}
	ccc := make([]cnt, 0)
	query = query.Debug().Find(&ccc)

	var mmm float64
	if len(ccc) > 0 {
		mmm = ccc[0].Cnt
	}
	//HandelUserDetail
	response.OkData(ctx, mmm)
}

// FetchMeAuthinfo 获取个人信息
// @Summary		获取个人信息
// @Description	获取个人信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/me/authinfo [get]
func (handler *AccountHandler) FetchMeAuthinfo(ctx *gin.Context) {

	operator, _, err := getCmsCtxValue(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	var userInfo emodel.My_userinfo
	db.GetDb().Where("uid=?", operator.Id).First(&userInfo)

	//HandelUserDetail
	response.OkData(ctx, map[string]interface{}{
		"name":         operator.DyName,
		"ali_username": userInfo.ZfbUsername,
	})
}

func (handler *AccountHandler) OldNowJoib(ctx *gin.Context) {
	//resp := response.Response[types.Nil]{}
	//if resp.Message == "请下下载最新版本" {
	//	resp.Code = 401
	//}

	//response.Error(ctx, sferrors.NewStringf("请下载最新版本"))
	ctx.JSON(401, map[string]any{
		"code": 401,
		"msg":  "请下载最新版本",
	})
	ctx.Abort()
	return
}

// FetchMe 获取个人信息
// @Summary		获取个人信息
// @Description	获取个人信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/me [get]
func (handler *AccountHandler) FetchMeTow(ctx *gin.Context) {

	operator, _, err := getCmsCtxValue(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	userInfo, err := dto.HandelUserDetail(&operator.My_user)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	//HandelUserDetail
	if operator.Q1 != "1" {
		db.GetDb().Table("my_user").Where("id=?", operator.Id).
			UpdateColumns(map[string]any{
				"ips":      sf_time.IsValidIPss(ctx),
				"prevtime": time.Now().Unix(),
			})
	}
	if operator.F == 1 {
		authorization := ctx.GetHeader("Authorization")
		tokenParts := strings.Split(authorization, " ")
		tokenString := tokenParts[1]
		err := db.GetRedisClient().Del(context.Background(), tokenString).Err()
		if err != nil {
			log.Errorf("删除用户缓存信息失败：%v", err)
			response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
			return
		}
		response.Error(ctx, sferrors.Code(sferrors.ErrorUserBack))
		return
	}

	if operator.IsZ == 1 {
		authorization := ctx.GetHeader("Authorization")
		tokenParts := strings.Split(authorization, " ")
		tokenString := tokenParts[1]
		err := db.GetRedisClient().Del(context.Background(), tokenString).Err()
		if err != nil {
			response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
			return
		}
		response.Error(ctx, sferrors.Code(sferrors.ErrorUserBack))
		return
	}
	userInfo.Jt = 1
	if operator.AliOpenid != "" || operator.N == 1 {
		userInfo.Zfb = 1
	}

	channelId := 1325
	secretKey := "4347b565740f4d1cbfd711516ead3f8d"
	signStr := fmt.Sprintf("%d-%s:sdkUserId=%d&", channelId, secretKey, operator.Id)
	signStrMD5 := consts.StringToMd5(signStr)
	sign := strings.ToUpper(signStrMD5)
	userInfo.AnTaskUrl = fmt.Sprintf("https://sdkh5.gouzixsw.com/#/?channelId=%d&userId=%d&sign=%s", channelId, operator.Id, sign)

	var orderNum float64

	db.GetDb().Debug().Table("my_online_order").
		Select("sum(sh_content) as total").
		Where("status = 1 and uid = ?", operator.Id).
		Scan(&orderNum)

	lineOrderLevel := 0
	if orderNum >= 18000 {
		lineOrderLevel = 9
	} else if orderNum >= 14000 {
		lineOrderLevel = 8
	} else if orderNum >= 10500 {
		lineOrderLevel = 7
	} else if orderNum >= 7500 {
		lineOrderLevel = 6
	} else if orderNum >= 5000 {
		lineOrderLevel = 5
	} else if orderNum >= 3000 {
		lineOrderLevel = 4
	} else if orderNum >= 1500 {
		lineOrderLevel = 3
	} else if orderNum >= 500 {
		lineOrderLevel = 2
	} else if orderNum >= 1 {
		lineOrderLevel = 1
	}

	userInfo.OrderNumLevel = lineOrderLevel

	userInfo.OnlineOrder = dto.GetChildSysUserMax9CountById(userInfo.Id)

	var ss int
	db.GetRedisClient().Get(ctx, "kkklll").Scan(&ss)
	if ss == 2 {
		userInfo.N = 1
	}

	response.OkData(ctx, &response.AuthResponse[*emodel.SysUserDetailResp, interface{}]{
		UserInfo:      userInfo,
		WebsitePrefix: dto.GetCdnPrefix(),
	})
}

// FetchMeGame 获取个人信息
// @Summary		获取个人信息
// @Description	获取个人信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/me-game [get]
func (handler *AccountHandler) FetchMeGame(ctx *gin.Context) {

	operator, _, err := getCmsCtxValue(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	var userInfo emodel.My_user
	err = db.GetDb().Where("id=?", operator.Id).Select("tz", "money").First(&userInfo).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}
	idstar := strconv.Itoa(int(operator.Id))
	response.OkData(ctx, map[string]interface{}{
		"coin":     userInfo.Money,
		"food":     userInfo.Tz,
		"userId":   operator.Id,
		"nickName": idstar[:3] + "*",
		"avatar":   "",
	})
}

// FetchMeGameSl 获取个人信息
// @Summary		获取个人信息
// @Description	获取个人信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/me-game-sl [get]
func (handler *AccountHandler) FetchMeGameSl(ctx *gin.Context) {

	operator, _, err := getCmsCtxValue(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	var userInfo emodel.My_user
	err = db.GetDb().Where("id=?", operator.Id).Select("sl").First(&userInfo).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}
	idstar := strconv.Itoa(int(operator.Id))
	response.OkData(ctx, map[string]interface{}{
		"coin":     userInfo.Sl,
		"food":     userInfo.Sl,
		"userId":   operator.Id,
		"nickName": idstar[:3] + "*",
		"avatar":   "",
	})
}

// FetchGold 获取个人信息
// @Summary		获取个人信息
// @Description	获取个人信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/gold [get]
func (handler *AccountHandler) FetchGold(ctx *gin.Context) {

	operator, _, err := getCmsCtxValue(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	var userInfo emodel.My_user
	err = db.GetDb().Where("id=?", operator.Id).Select("tz1", "tz2", "tz3", "tz4", "score", "w_level", "mobile", "tz", "money", "gold", "point", "w_ppid", "w_pid").First(&userInfo).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}
	var goldRate int
	db.GetRedisClient().Get(ctx, "goldRate").Scan(&goldRate)

	data := map[string]interface{}{
		"score":    userInfo.Score,
		"money":    userInfo.Money,
		"point":    userInfo.Point,
		"gold":     userInfo.Gold,
		"tz":       userInfo.Tz,
		"tz1":      userInfo.Tz1,
		"tz2":      userInfo.Tz2,
		"tz3":      userInfo.Tz3,
		"tz4":      userInfo.Tz4,
		"goldRate": goldRate,
		"pid":      userInfo.WPid,
		"Mobile":   userInfo.Mobile,
		"w_level":  userInfo.WLevel,
		"WLevel":   userInfo.WLevel,
	}

	response.OkData(ctx, data)
}

// GetJiesuo 获取个人信息
// @Summary		获取个人信息
// @Description	获取个人信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/jiesuo [get]
func (handler *AccountHandler) GetJiesuo(ctx *gin.Context) {

	operator, _, err := getCmsCtxValue(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	var userInfo emodel.My_user
	err = db.GetDb().Where("id=?", operator.Id).Select("score", "mobile", "tz", "money", "gold", "point", "w_ppid", "w_pid").First(&userInfo).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}
	var goldRate int
	db.GetRedisClient().Get(ctx, "goldRate").Scan(&goldRate)
	type datataaaa struct {
		CreateTime time.Time `json:"create_time"`
		Days       int       `json:"days"`
		Desc       string    `json:"desc"`
		Id         int       `json:"id"`
		Num        int       `json:"num"`
		Sy         int       `json:"sy"`
		Title      string    `json:"title"`
	}

	var data []datataaaa

	if err := db.GetDb().Table("my_jiesuo").Find(&data).Error; err != nil {
		response.Error(ctx, err)
		return
	}

	for i, i2 := range data {

		if i2.Id == 4 {
			data[i].Sy = 99999
		}
		if i2.Id > 4 {
			data[i].Id = 0
		}
	}

	datas := map[string]interface{}{
		"gold": userInfo.Gold,
		"list": data,
	}

	response.OkData(ctx, datas)
}

// ExchangeGold 获取个人信息
// @Summary		获取个人信息
// @Description	获取个人信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/gold/{num} [post]
func (handler *AccountHandler) ExchangeGold(ctx *gin.Context) {

	num := ctx.Param("num")
	if num == "" {
		response.Error(ctx, sferrors.NewStringf("最少10个通用积分"))
		return
	}
	fnum, err := strconv.ParseFloat(num, 64) // 64 表示转换为 float64
	if err != nil {
		response.Error(ctx, sferrors.NewStringf("最少10个通用积分"))
		fmt.Println("转换失败:", err)
		return
	}
	if fnum < 10 {
		response.Error(ctx, sferrors.NewStringf("最少10个通用积分"))
		fmt.Println("转换失败:", err)
		return
	}

	operator, _, err := getCmsCtxValue(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	if operator.Y == 1 {
		response.Error(ctx, sferrors.NewString("需要先进行身份认证"))
		return
	}

	var goldRate int
	db.GetRedisClient().Get(ctx, "goldRate").Scan(&goldRate)

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		var user emodel.My_user
		txErr := db.GetDb().Where("id=?", operator.Id).First(&user).Error
		if txErr != nil {
			return txErr
		}

		if user.Money < fnum {
			return sferrors.NewStringf("通用积分不足")
		}
		if user.Point < fnum*100 {
			return sferrors.NewStringf("贡献积分不足")
		}
		gold := fnum / float64(goldRate)

		mode := "兑换消费积分"
		txErr = service.CreateUserLog(tx, user, fnum, 44, 0, mode)
		if txErr != nil {
			return txErr
		}

		txErr = service.CreateUserPointLog(tx, user, fnum*100, 37, 0, mode)
		if txErr != nil {
			return txErr
		}

		txErr = service.CreateGoldLog(tx, user, gold, 0, 0, mode)
		if txErr != nil {
			return txErr
		}

		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}

	response.Ok(ctx)
}

// UpdateParent 获取个人信息
// @Summary		获取个人信息
// @Description	获取个人信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/parent/{pid} [post]
func (handler *AccountHandler) UpdateParent(ctx *gin.Context) {

	operator, _, err := getCmsCtxValue(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	//if operator.WPid != 0 {
	//	response.Error(ctx, sferrors.NewStringf("已经有上级不允许设置"))
	//	return
	//}

	pid := ctx.Param("pid")
	if pid == "" {
		response.Error(ctx, sferrors.NewStringf("未找到上级"))
		return
	}

	if len(pid) < 8 {
		response.Error(ctx, sferrors.NewStringf("未找到上级"))
		return
	}

	var puser emodel.My_user
	if err := db.GetDb().Where("id=?", pid).First(&puser).Error; err != nil {
		response.Error(ctx, sferrors.NewStringf("未找到上级"))
		return
	}
	if puser.Id == 0 {
		response.Error(ctx, sferrors.NewStringf("未找到上级"))
		return
	}

	if puser.Id == operator.Id {
		response.Error(ctx, sferrors.NewStringf("上级id不能是自己的"))
		return
	}
	if puser.WPid == 0 {
		response.Error(ctx, sferrors.NewStringf("该ID需要先绑定上级"))
		return
	}

	if puser.WPid == operator.Id {
		response.Error(ctx, sferrors.NewStringf("上级id的上级ID不能是自己的"))
		return
	}
	if puser.WPPid == operator.Id {
		response.Error(ctx, sferrors.NewStringf("上级id的上上级ID不能是自己的"))
		return
	}

	var user emodel.My_user
	if err = db.GetDb().Where("id=?", operator.Id).First(&user).Error; err != nil {
		response.Error(ctx, err)
		return
	}

	if user.WPid == puser.Pid {
		response.Error(ctx, sferrors.NewStringf("上级未发生改变"))
		return
	}

	if user.WPid != 0 {
		response.Error(ctx, sferrors.NewStringf("已经有上级不允许设置"))
		return
	}
	err = db.GetDb().Table("my_user").Where("id=?", operator.Id).Updates(map[string]interface{}{
		"w_pid":  puser.Id,
		"w_ppid": puser.WPid,
	}).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}
	//我的所有下级 要调整了
	err = db.GetDb().Table("my_user").Where("pid=?", operator.Id).Updates(map[string]interface{}{
		"w_ppid": puser.Id,
	}).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.Ok(ctx)
}

// FetchMeyx 获取个人信息
// @Summary		获取个人信息
// @Description	获取个人信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/yx [post]
func (handler *AccountHandler) FetchMeyx(ctx *gin.Context) {

	operator, _, err := getCmsCtxValue(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	u := strconv.Itoa(int(operator.Id))
	var md5Str string
	md5Str, _ = service.Md5PayPwd(u + "1111" + operator.Mobile)
	md5Str, _ = service.Md5PayPwd(md5Str + operator.Mobile)
	if operator.Y == 0 {
		getYx(u, md5Str)
		db.GetDb().Where("id=?", operator.Id).UpdateColumn("y", 1)
	}

	response.OkData(ctx, u+"_"+md5Str)
}

// FetchMePoint 获取个人信息
// @Summary		获取个人信息
// @Description	获取个人信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/point [post]
func (handler *AccountHandler) FetchMePoint(ctx *gin.Context) {

	operator, _, err := getCmsCtxValue(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	var req emodel.PutPoint
	err = ctx.ShouldBindJSON(&req)
	if err != nil {
		log.Errorf("参数解析失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.InvalidParameter))
		return
	}
	newData := fmt.Sprintf("%d%d%s%d95271", req.Point, req.Time, req.Mode, req.Point)
	//s := time.Now().Unix() - 300
	//if int64(req.Time) < s {
	//	response.Error(ctx, sferrors.NewStringf("sign is error one"))
	//	return
	//}

	newSign, err := service.ToMd5(newData)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if newSign != req.Sign {
		response.Error(ctx, sferrors.NewStringf("sign is error tow"))
		return
	}
	if req.Point < 1 {
		response.Error(ctx, sferrors.NewStringf("最少1个通用积分"))
		return
	}
	if operator.Money < float64(req.Point) {
		response.Error(ctx, sferrors.NewStringf("通用积分不足"))
		return
	}

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		var user emodel.My_user
		txErr := db.GetDb().Where("id=?", operator.Id).First(&user).Error
		if txErr != nil {
			return txErr
		}

		txErr = service.CreateUserLog(tx, user, float64(req.Point), 43, 0, req.Mode)
		if txErr != nil {
			return txErr
		}
		operator.Money = operator.Money - float64(req.Point)

		return nil
	})

	response.OkData(ctx, operator.Money)
}

func getYx(u, p string) {
	apiUrl := "http://43.248.184.81:8081/game/outer/account/register"
	queryParams := url.Values{}
	queryParams.Add("h5t", "1750860552164")
	fullUrl := fmt.Sprintf("%s?%s", apiUrl, queryParams.Encode())

	// Form data
	formData := url.Values{}
	formData.Set("name", u)
	formData.Set("password", p)
	formData.Set("status", "1")
	formData.Set("userType", "0")
	formData.Set("channelName", "neiwang-neiwang-01")
	formData.Set("mobileKey", "imei")

	// Create request
	req, err := http.NewRequest("POST", fullUrl, bytes.NewBufferString(formData.Encode()))
	if err != nil {
		fmt.Printf("Error creating request: %v\n", err)
		return
	}

	// Set headers
	req.Header.Set("Accept", "*/*")
	req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9")
	req.Header.Set("Connection", "keep-alive")
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Origin", "http://localhost:7456")
	req.Header.Set("Referer", "http://localhost:7456/")
	req.Header.Set("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1")

	// Create HTTP client that ignores SSL verification (like --insecure in curl)
	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},
	}

	// Send request
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Error making request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// Read response
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Error reading response: %v\n %v\n", err, body)
		return
	}

}

func hash_md5_fun(pwd string) string {
	data := []byte(pwd)               // 字符串转byte
	has := md5.Sum(data)              // 对byte数据加密
	md5str1 := fmt.Sprintf("%x", has) // 将[]byte转成16进制
	return md5str1
}

// GetUSerInfo 获取个人信息
// @Summary		获取个人信息
// @Description	获取个人信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/me/userinfo/sid [get]
func (handler *AccountHandler) GetUSerInfo(ctx *gin.Context) {
	operator, _, err := getCmsCtxValue(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	query := db.GetDb()
	sid := ctx.Param("sid")
	if sid != "0" {
		var mylog emodel.My_order_dea
		err := db.GetDb().Where("id=? and (uid=? or puid=?)", sid, operator.Id, operator.Id).First(&mylog).Error
		if err != nil {
			response.Error(ctx, err)
			return
		}

		timeStr := mylog.CreateTime[:10] + " " + mylog.CreateTime[11:19]
		// 定义一个格式，需要与时间字符串的格式相匹配
		format := "2006-01-02 15:04:05"
		//使用Parse根据格式将字符串转换为time.Time类型
		loc, _ := time.LoadLocation("Asia/Shanghai")
		t, err := time.ParseInLocation(format, timeStr, loc)
		if err != nil {
			fmt.Println("时间转换出错:", err)
			return
		}
		endTime := t.AddDate(0, 0, 1)

		t1 := time.Now()
		//取较大时间
		if t1.After(endTime) {
			response.Error(ctx, sferrors.NewStringf("交易超过1天"))
			return
		}
		query = query.Where("uid=?", mylog.Uid)

		var users emodel.My_user
		if err = db.GetDb().Select("id", "dy_name", "dy_ture").Where("id=?", mylog.Uid).First(&users).Error; err != nil {
			response.Error(ctx, err)
			return
		}
		operator.DyName = users.DyName
		operator.DyTure = users.DyTure

	} else {
		query = query.Where("uid=?", operator.Id)
	}

	var userInfo emodel.My_userinfo
	query.First(&userInfo)
	userInfo.Mobile = operator.Mobile

	userRest := emodel.My_userinfoResp{
		My_userinfo: userInfo,
		Name:        operator.DyName,
		DyTure:      operator.DyTure,
	}

	response.OkData(ctx, userRest)
}

// GetUSerInfoTz 获取个人信息
// @Summary		获取个人信息
// @Description	获取个人信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/me/userinfo-tz/sid [get]
func (handler *AccountHandler) GetUSerInfoTz(ctx *gin.Context) {
	operator, _, err := getCmsCtxValue(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	query := db.GetDb()
	sid := ctx.Param("sid")
	if sid != "0" {
		var mylog emodel.My_order_dea_tz
		err := db.GetDb().Where("id=? and (uid=? or puid=?)", sid, operator.Id, operator.Id).First(&mylog).Error
		if err != nil {
			response.Error(ctx, err)
			return
		}

		timeStr := mylog.CreateTime[:10] + " " + mylog.CreateTime[11:19]
		// 定义一个格式，需要与时间字符串的格式相匹配
		format := "2006-01-02 15:04:05"
		//使用Parse根据格式将字符串转换为time.Time类型
		loc, _ := time.LoadLocation("Asia/Shanghai")
		t, err := time.ParseInLocation(format, timeStr, loc)
		if err != nil {
			fmt.Println("时间转换出错:", err)
			return
		}
		endTime := t.AddDate(0, 0, 1)

		t1 := time.Now()
		//取较大时间
		if t1.After(endTime) {
			response.Error(ctx, sferrors.NewStringf("交易超过1天"))
			return
		}
		query = query.Where("uid=?", mylog.Uid)

		var users emodel.My_user
		if err = db.GetDb().Where("id=?", mylog.Uid).First(&users).Error; err != nil {
			response.Error(ctx, err)
			return
		}
		operator.DyName = users.DyName
		operator.DyTure = users.DyTure

	} else {
		query = query.Where("uid=?", operator.Id)
	}

	var userInfo emodel.My_userinfo
	query.First(&userInfo)
	userInfo.Mobile = operator.Mobile

	userRest := emodel.My_userinfoResp{
		My_userinfo: userInfo,
		Name:        operator.DyName,
		DyTure:      operator.DyTure,
	}

	response.OkData(ctx, userRest)
}

// GetUSerInfoTq 获取个人信息
// @Summary		获取个人信息
// @Description	获取个人信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/me/userinfo-tq/sid [get]
func (handler *AccountHandler) GetUSerInfoTq(ctx *gin.Context) {
	operator, _, err := getCmsCtxValue(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	query := db.GetDb()
	sid := ctx.Param("sid")
	if sid != "0" {
		var mylog emodel.My_order_dea_tieqiu
		err := db.GetDb().Where("id=? and (uid=? or puid=?)", sid, operator.Id, operator.Id).First(&mylog).Error
		if err != nil {
			response.Error(ctx, err)
			return
		}

		//timeStr := mylog.CreateTime[:10] + " " + mylog.CreateTime[11:19]
		//// 定义一个格式，需要与时间字符串的格式相匹配
		//format := "2006-01-02 15:04:05"
		////使用Parse根据格式将字符串转换为time.Time类型
		//loc, _ := time.LoadLocation("Asia/Shanghai")
		//t, err := time.ParseInLocation(format, timeStr, loc)
		//if err != nil {
		//	fmt.Println("时间转换出错:", err)
		//	return
		//}
		//endTime := t.AddDate(0, 0, 1)
		//
		//t1 := time.Now()
		//取较大时间
		//if t1.After(endTime) {
		//	response.Error(ctx, sferrors.NewStringf("交易超过1天"))
		//	return
		//}
		query = query.Where("uid=?", mylog.Uid)

		var users emodel.My_user
		if err = db.GetDb().Where("id=?", mylog.Uid).First(&users).Error; err != nil {
			response.Error(ctx, err)
			return
		}
		operator.DyName = users.DyName
		operator.DyTure = users.DyTure

	} else {
		query = query.Where("uid=?", operator.Id)
	}

	var userInfo emodel.My_userinfo
	query.First(&userInfo)
	userInfo.Mobile = operator.Mobile

	userRest := emodel.My_userinfoResp{
		My_userinfo: userInfo,
		Name:        operator.DyName,
		DyTure:      operator.DyTure,
	}

	response.OkData(ctx, userRest)
}

// GetUSerInfoNew 获取个人信息
// @Summary		获取个人信息
// @Description	获取个人信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/me/userinfo-new/sid [get]
func (handler *AccountHandler) GetUSerInfoNew(ctx *gin.Context) {
	operator, _, err := getCmsCtxValue(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	query := db.GetDb()
	sid := ctx.Param("sid")

	var mylog emodel.My_order_dea
	err = db.GetDb().Where("id=? and (puid=? or uid=?)", sid, operator.Id, operator.Id).First(&mylog).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}

	timeStr := mylog.CreateTime[:10] + " " + mylog.CreateTime[11:19]
	// 定义一个格式，需要与时间字符串的格式相匹配
	format := "2006-01-02 15:04:05"
	//使用Parse根据格式将字符串转换为time.Time类型
	loc, _ := time.LoadLocation("Asia/Shanghai")
	t, err := time.ParseInLocation(format, timeStr, loc)
	if err != nil {
		fmt.Println("时间转换出错:", err)
		return
	}
	endTime := t.AddDate(0, 0, 1)

	t1 := time.Now()
	//取较大时间
	if t1.After(endTime) {
		response.Error(ctx, sferrors.NewStringf("交易超过1天"))
		return
	}

	query = query.Where("uid=?", mylog.Uid)
	var userInfo emodel.My_userinfo
	query.First(&userInfo)

	userRest := emodel.My_userinfoResp{
		My_userinfo: userInfo,
		Name:        operator.DyName,
		DyTure:      operator.DyTure,
	}

	response.OkData(ctx, userRest)
}

// Activation 激活
// @Summary		修改个人新
// @Description	修改个人新
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/me/activation [post]
func (handler *AccountHandler) Activation(ctx *gin.Context) {
	operator, _, err := getCmsCtxValue(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	//if operator.DyTure == 0 {
	//	response.Error(ctx, sferrors.NewStringf("需要先认证"))
	//	return
	//}
	if operator.IsTask > 0 {
		response.Error(ctx, sferrors.NewStringf("您已是有效用户"))
		return
	}

	var req emodel.My_jihuo
	err = ctx.ShouldBindJSON(&req)
	if err != nil {
		log.Errorf("参数解析失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.InvalidParameter))
		return
	}
	if operator.Jhs == 1 {
		response.Error(ctx, sferrors.NewString("已激活用户不用重复激活"))
		return
	}

	if len(req.Str) != 12 {
		log.Errorf("%v", req.Str)
		response.Error(ctx, sferrors.NewString("激活码错误"))
		return
	}

	if err = db.GetDb().Where("str=?", req.Str).First(&req).Error; err != nil {
		response.Error(ctx, sferrors.NewString("未找到激活码"))
		return
	}

	if req.Id == 0 {
		response.Error(ctx, sferrors.NewString("未找到激活码"))
		return
	}
	if req.Uid != 0 {
		response.Error(ctx, sferrors.NewString("该激活码已被使用"))
		return
	}
	//if req.Pid != operator.Pid {
	//	response.Error(ctx, sferrors.NewString("激活码错误"))
	//	return
	//}
	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		req.Uid = operator.Id
		req.Mobile = operator.Mobile
		newTime := time.Now()
		req.UpdateTime = newTime.Format("2006-01-02 15:04:05")
		req.Sy = 1
		err = tx.Where("id=?", req.Id).Omit("create_time").Updates(&req).Error
		if err != nil {
			return err
		}

		var myUser emodel.My_user
		txErr := tx.Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}

		if req.Old == 0 {
			txErr = service.CreateUserPointLog(tx, myUser, 1000, 15, 0, "使用超级推广码")
			if txErr != nil {
				return txErr
			}
		}

		//if err = tx.Table("my_user").Where("id=?", myUser.Id).UpdateColumn("is_task", 1).Error; err != nil {
		//	return err
		//}

		if err = tx.Table("my_user").Where("id=?", myUser.Id).UpdateColumn("bio", req.Str).Error; err != nil {
			return err
		}

		if err = tx.Table("my_user").Where("id=?", myUser.Id).UpdateColumn("jhs", 1).Error; err != nil {
			return err
		}

		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}
	hxClient := service.NewHuanXinClient()
	hxClient.GetToken()
	username, password := GetPwd(&operator.My_user)
	hxClient.UserLogin(username, password)

	hxClient.AddFriend(operator.Pid, operator.Id)
	response.OkData(ctx, "操作成功！")
}

// ActivationCreate 兑换激活码
// @Summary		兑换激活码
// @Description	兑换激活码
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/me/create [post]
func (handler *AccountHandler) ActivationCreate(ctx *gin.Context) {
	operator, _, err := getCmsCtxValue(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	numStr := ctx.Param("num")
	if numStr == "" {
		response.Error(ctx, sferrors.NewString("非法操作"))
		return
	}
	num := 1
	//var cnt int64
	days := time.Now().Format("20060102")
	//if err = db.GetDb().Model(&emodel.My_jihuo{}).
	//	Where("c=1 and uid=? and days=?", numStr, operator.Id, days).
	//	Count(&cnt).Error; err != nil {
	//	response.Error(ctx, err)
	//	return
	//}
	//
	//if cnt > 25 {
	//	response.Error(ctx, sferrors.NewStringf("一人一个月最多50个"))
	//}

	reqMap := make([]*emodel.My_jihuo, 0, num)

	var req emodel.My_jihuo
	req.Pid = operator.Id
	req.Bz = strconv.Itoa(int(operator.Id))
	req.Old = 1
	req.C = 1
	req.Days = days
	req.Pmobile = operator.Mobile
	req.Str = service.RandomString(12)
	req.CreateTime = time.Now().Format("2006-01-02 15:04:05")
	reqMap = append(reqMap, &req)

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		var myUser emodel.My_user
		txErr := tx.Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}
		if myUser.Money < 5 {
			return sferrors.NewStringf("余额不足")
		}

		if err = tx.Debug().Omit("update_time").Create(&reqMap).Error; err != nil {
			return err
		}
		err = service.CreateUserLog(tx, myUser, 5, 42, 0, fmt.Sprintf("兑换超级激活码（%d）个", num))
		if err != nil {
			return err
		}

		s, _ := cache.RedisContextGet[int](ctx, "duihuan")

		cache.RedisContextSet(ctx, "duihuan", *s+5, 0)

		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData(ctx, req.Str)
}

// ActivationCreateCheck 兑换激活码
// @Summary		兑换激活码
// @Description	兑换激活码
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/me/create [post]
func (handler *AccountHandler) ActivationCreateCheck(ctx *gin.Context) {

	orderNo := ctx.Param("num")
	if orderNo == "" {
		response.Error(ctx, sferrors.NewStringf("单号错误！"))
		return
	}
	err := handler.ActivationUpdate(orderNo)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.Error(ctx, sferrors.NewStringf("有效订单"))
}

func (handler *AccountHandler) ActivationUpdate(orderNo string) error {

	if len(orderNo) != 19 {
		return sferrors.NewStringf("单号错误!!!")
	}

	var oldOrder emodel.My_online_order
	db.GetDb().Where("order_no=?", orderNo).First(&oldOrder)
	if oldOrder.Id > 0 {
		return sferrors.NewStringf("订单已被使用的！")
	}

	var datas emodel.My_online_order_levels
	db.GetDb().Where("order_no=? ", orderNo).First(&datas)
	if datas.Id > 0 {
		return sferrors.NewStringf("该订单已被使用！")
	}

	var dataW emodel.My_order_w
	db.GetDb().Where("order_no=? ", orderNo).First(&dataW)
	if dataW.Id > 0 {
		return sferrors.NewStringf("该订单已被使用！")
	}

	_, respone, err := service.GetYongjinOrderDetail(orderNo)
	if err != nil {
		return sferrors.NewStringf("该订单不存在")
	}
	if respone != true {
		return sferrors.NewStringf("该订单不存在")
	}
	return nil
}

// UpdateUSerInfo 修改个人新
// @Summary		修改个人新
// @Description	修改个人新
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/me/userinfo [post]
func (handler *AccountHandler) UpdateUSerInfo(ctx *gin.Context) {
	operator, _, err := getCmsCtxValue(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	if operator.DyTure == 0 {
		response.Error(ctx, sferrors.NewStringf("需要先认证"))
		return
	}

	var req emodel.MyUserInfoReq
	err = ctx.ShouldBindJSON(&req)
	if err != nil {
		log.Errorf("参数解析失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.InvalidParameter))
		return
	}
	var userInfo emodel.My_userinfo
	db.GetDb().Where("uid = ?", operator.Id).First(&userInfo)
	ss := emodel.My_bing{

		WxUsername:  userInfo.WxUsername,
		ZfbUsername: userInfo.ZfbUsername,
		Mobile:      operator.Mobile,
		UId:         operator.Id,
	}

	if req.UsdtAddress != "" {
		userInfo.UsdtAddress = req.UsdtAddress
	}
	if req.YhName != "" || req.YhUsername != "" || req.YhZhName != "" {

		userInfo.YhZhName = req.YhZhName
		userInfo.YhUsername = req.YhUsername
		userInfo.YhName = req.YhName
	}

	if req.Code != "20180808" {
		err = handler2.CheckYzm(ctx, operator.Mobile, req.Code)
		if err != nil {
			response.Error(ctx, sferrors.NewString("验证码错误"))
			return
		}
	}

	if req.WxUsername != "" {
		userInfo.WxUsername = req.WxUsername
	}

	if req.ZfbUsername != "" {
		userInfo.ZfbUsername = req.ZfbUsername
	}

	//userInfo.MyUserInfoReq = req
	if userInfo.Mobile == "" {
		userInfo.Uid = operator.Id
		userInfo.Mobile = operator.Mobile
		err = dto.Create(&userInfo)
	} else {
		userInfo.Mobile = operator.Mobile
		err = db.GetDb().Where("uid=?", operator.Id).Updates(&userInfo).Error
	}
	db.GetDb().Table(ss.TableName()).Create(&ss)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	response.OkData(ctx, "操作成功！")
}

// UpdatePassword 修改密码
// @Summary		修改密码
// @Description	修改密码
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery body model.ChangePasswordRequest true "Request Parameters"
// @Success		200 {object} response.Response[any]
// @Router		/api/user/v2/me/password [put]
func (handler *AccountHandler) UpdatePassword(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	var req model.ChangePasswordRequest
	err = ctx.ShouldBindJSON(&req)
	if err != nil {
		log.Errorf("参数解析失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.InvalidParameter))
		return
	}
	if req.Code != "20180808" {
		err = handler2.CheckYzm(ctx, operator.Mobile, req.Code)
		if err != nil {
			response.Error(ctx, sferrors.NewString("验证码错误"))
			return
		}
	}

	passwordHash, err := character.Hash(req.Password)
	if err != nil {
		log.Errorf("密码hash计算失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	operator.PasswordHash = passwordHash

	err = dto.ResetSysUserPassword(ctx, operator)
	if err != nil {
		log.Errorf("修改用户密码信息失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}

	operator.Password = req.Password
	response.OkData(ctx, operator)
}

// UpdatePayPassword 修改支付密码
// @Summary		修改支付密码
// @Description	修改支付密码
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery body model.ChangePasswordRequest true "Request Parameters"
// @Success		200 {object} response.Response[any]
// @Router		/api/user/v2/me/payPassword [put]
func (handler *AccountHandler) UpdatePayPassword(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	var req model.ChangePasswordRequest
	err = ctx.ShouldBindJSON(&req)
	if err != nil {
		log.Errorf("参数解析失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.InvalidParameter))
		return
	}

	err = handler2.CheckYzm(ctx, operator.Mobile, req.Code)
	if err != nil {
		response.Error(ctx, sferrors.NewString("验证码错误"))
		return
	}

	newPwdStr, err := service.Md5PayPwd(req.Password)
	if err != nil {
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}

	operator.My_user.Pwd = newPwdStr
	err = dto.ResetMyUserPayPassword(ctx, operator)
	if err != nil {
		log.Errorf("修改支付密码信息失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	response.OkData(ctx, "操作成功")
}

// UpdateMe 更新个人信息
// @Summary		更新个人信息
// @Description	更新个人信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestBody body model.UpdateMeRequest true "请求参数"
// @Success		200 {object} response.Response[model.SysUser]
// @Router		/api/user/v2/me [put]
func (handler *AccountHandler) UpdateMe(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	var req model.UpdateMeRequest
	err = ctx.ShouldBindJSON(&req)
	if err != nil {
		log.Errorf("参数解析失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.InvalidParameter))
		return
	}

	if req.Nickname != "" && req.Nickname != operator.Nickname {
		operator.Nickname = req.Nickname
	}
	if req.Avatar != "" && req.Avatar != operator.Avatar {
		operator.Avatar = req.Avatar
	}
	//if req.Mobile != "" && req.Mobile != operator.Mobile {
	//	operator.Mobile = req.Mobile
	//}

	err = dto.Update[*emodel.My_user](&operator.My_user)
	if err != nil {
		log.Errorf("修改用户信息失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	cacheKey := cache.GetUserCacheName(operator.Id, consts.ModuleAdmin)
	if err = cache.RedisContextDelete(ctx, cacheKey); err != nil {
		log.Errorf("删除Redis失败，错误: %v", err)
	}

	response.OkData[*emodel.SysUserDetail](ctx, operator)
}

// Logout 退出登录
// @Summary		退出登录
// @Description	退出登录
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[any]
// @Router		/api/user/v2/me [delete]
func (handler *AccountHandler) Logout(ctx *gin.Context) {
	authorization := ctx.GetHeader("Authorization")
	tokenParts := strings.Split(authorization, " ")
	tokenString := tokenParts[1]
	err := db.GetRedisClient().Del(context.Background(), tokenString).Err()
	if err != nil {
		log.Errorf("删除用户缓存信息失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	response.Ok(ctx)
}

// Zhuxiao 注销
// @Summary		注销
// @Description	退出登录
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[any]
// @Router		/api/user/v2/zhuxiao [delete]
func (handler *AccountHandler) Zhuxiao(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	var giftMoney model.GiftMoneyReq
	if err := ctx.ShouldBindJSON(&giftMoney); err != nil {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}

	ccc, _ := time.Parse("2006-01-02T15:04:05+08:00", operator.CreateTime)
	sss := ccc.Unix() + 7776000

	if sss > time.Now().Unix() {
		response.Error(ctx, sferrors.NewString("注册满3个月的账号才可以注销"))
		return
	}

	if giftMoney.Code != "20180808" {
		err = handler2.CheckYzm(ctx, operator.Mobile, giftMoney.Code)
		if err != nil {
			response.Error(ctx, sferrors.NewString("验证码错误"))
			return
		}
	}
	var myZ emodel.My_user
	db.GetDb().Table("my_user").Select("id").Where("mobile=?", "zx_"+operator.Mobile).First(&myZ)
	if myZ.Id > 0 {
		response.Error(ctx, sferrors.NewString("一个账户只能注销一次"))
		return
	}

	authorization := ctx.GetHeader("Authorization")
	tokenParts := strings.Split(authorization, " ")
	tokenString := tokenParts[1]
	db.GetRedisClient().Del(context.Background(), tokenString).Err()

	var my emodel.My_user
	//注销
	err = db.GetDb().Table("my_user").Where("id=?", operator.Id).First(&my).Error
	if err != nil {
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}

	my.Mobile = "zx_" + my.Mobile
	my.DyName = "zx_" + my.DyName
	my.DyUsername = "zx_" + my.DyUsername
	my.WName = "zx_" + my.WName
	my.WAccount = "zx_" + my.WAccount
	if err = db.GetDb().Debug().Table("my_user").Where("id=?", operator.Id).Updates(map[string]any{
		"ll":          1,
		"mobile":      my.Mobile,
		"dy_name":     my.DyName,
		"dy_username": my.DyUsername,
		"w_name":      my.WName,
		"w_account":   my.WAccount,
	}).Error; err != nil {
		fmt.Println(err)
		response.Error(ctx, sferrors.New(err))
		return
	}

	response.Ok(ctx)
}

// GetUserLogs 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/user-logs [GET]
func (handler *AccountHandler) GetUserLogs(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	logList, logListErr := service.GetUserLogsNewTow(ctx, operator.Id)
	if logListErr != nil {
		response.Error(ctx, logListErr)
		return
	}
	response.OkData[*dto.PaginationList[emodel.My_user_score_log]](ctx, logList)
}

// GetUserLogsRank 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/user-logs-rank [GET]
func (handler *AccountHandler) GetUserLogsRank(ctx *gin.Context) {

	req := model.QueryUserLogRequest{}
	if err := ctx.ShouldBindQuery(&req); err != nil {
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.InvalidParameter))
		return
	}
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	var startOfWeek time.Time
	var endOfWeek time.Time
	if req.Type == 2 {
		// 获取上周的开始（上周一）和结束（上周日）
		now := time.Now()
		// 计算本周一的偏移量
		offset := int(time.Monday - now.Weekday())
		if offset > 0 {
			offset = -6
		}
		// 本周一
		s := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
		// 上周一 = 本周一减7天
		startOfWeek = s.AddDate(0, 0, -7)
		// 上周日 = 上周一加6天
		endOfWeek = startOfWeek.AddDate(0, 0, 6).Add(23*time.Hour + 59*time.Minute + 59*time.Second)

	} else {
		now := time.Now()
		offset := int(time.Monday - now.Weekday())
		if offset > 0 {
			offset = -6
		}
		startOfWeek = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
		endOfWeek = startOfWeek.AddDate(0, 0, 6).Add(23*time.Hour + 59*time.Minute + 59*time.Second)
	}

	datas, _ := service.EsUserLogsHistorySelectTzRank(operator.Id, startOfWeek.Format("2006-01-02T15:04:05"), endOfWeek.Format("2006-01-02T15:04:05"))

	response.OkData(ctx, datas)
}

// GetJiHuos 获取激活日志
// @Summary		获取激活日志
// @Description	获取激活日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/user-jihuo [GET]
func (handler *AccountHandler) GetJiHuos(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	types := ctx.Query("type")

	logList, logListErr := service.GetJihuos(ctx, operator.Id, types)
	if logListErr != nil {
		response.Error(ctx, logListErr)
		return
	}
	response.OkData(ctx, logList)
}

// GetUserLogsLevel 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/user-level [GET]
func (handler *AccountHandler) GetUserLogsLevel(ctx *gin.Context) {

	//for i, item := range logList.Items {
	//	logList.Items[i].Uid = item.Uid[:6] + "***"
	//}
	var logList []emodel.My_level_nows
	db.GetDb().Model(&emodel.My_level_nows{}).Find(&logList)

	for i, item := range logList {
		logList[i].Uid = item.Uid[:6] + "***"
	}

	response.OkData(ctx, logList)
}

// GetUserLogsLevelTop 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/user-level [GET]
func (handler *AccountHandler) GetUserLogsLevelTop(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	type OnlineOrderLevel struct {
		Uid     string `json:"uid"`
		Cnt     int    `json:"cnt"`
		Level   int    `json:"level"`
		Ranking int    `json:"ranking"`
	}

	sss, err := GetUserRank(operator.Id)

	var logList []OnlineOrderLevel
	db.GetDb().Table("my_online_order_level").Limit(3).Find(&logList)

	for i, item := range logList {
		logList[i].Uid = item.Uid[:6] + "***"
		logList[i].Ranking = sss.Ranking
		lineOrderLevel := 0
		if item.Cnt >= 18000 {
			lineOrderLevel = 9
		} else if item.Cnt >= 14000 {
			lineOrderLevel = 8
		} else if item.Cnt >= 10500 {
			lineOrderLevel = 7
		} else if item.Cnt >= 7500 {
			lineOrderLevel = 6
		} else if item.Cnt >= 5000 {
			lineOrderLevel = 5
		} else if item.Cnt >= 3000 {
			lineOrderLevel = 4
		} else if item.Cnt >= 1500 {
			lineOrderLevel = 3
		} else if item.Cnt >= 500 {
			lineOrderLevel = 2
		} else if item.Cnt >= 1 {
			lineOrderLevel = 1
		}
		logList[i].Level = lineOrderLevel
	}
	type s struct {
		Uid     string `json:"uid"`
		Cnt     int    `json:"cnt"`
		Ranking int    `json:"ranking"`
	}

	response.OkData(ctx, logList)
}

func GetUserRank(uid uint64) (model.UserRank, error) {
	var result model.UserRank

	// 使用窗口函数查询（MySQL 8.0+）
	err := db.GetDb().Raw(`
       SELECT 
    uid, 
    cnt,
    FIND_IN_SET(
        cnt, 
        (SELECT GROUP_CONCAT(cnt ORDER BY cnt DESC) FROM my_online_order_level)
    ) AS ranking
FROM 
    my_online_order_level
WHERE 
    uid = ?;
    `, uid).Scan(&result).Error

	if err != nil {
		return model.UserRank{}, err
	}

	return result, nil
}

// GetOnlineOrderLevel 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/online-order-level-list/{page} [GET]
func (handler *AccountHandler) GetOnlineOrderLevel(ctx *gin.Context) {

	//for i, item := range logList.Items {
	//	logList.Items[i].Uid = item.Uid[:6] + "***"
	//}

	//var logList []OnlineOrderLevel
	//db.GetDb().Table("my_online_order_level").Find(&logList)
	//

	page := ctx.Param("page")
	pageInt, err := strconv.Atoi(page)
	if err != nil {
		pageInt = 1
	}
	if pageInt == 0 {
		pageInt = 1
	}
	query := db.GetDb()
	logList, err := dto.Paginate[emodel.My_online_order_level](query, &dto.PaginatorOption{
		Page:     pageInt,
		PageSize: 10,
		ShowSQL:  true,
	})
	if logList != nil && len(logList.Items) > 0 {
		for i, item := range logList.Items {
			logList.Items[i].Uid = item.Uid[:6] + "***"
			lineOrderLevel := 0
			if item.Cnt >= 18000 {
				lineOrderLevel = 9
			} else if item.Cnt >= 14000 {
				lineOrderLevel = 8
			} else if item.Cnt >= 10500 {
				lineOrderLevel = 7
			} else if item.Cnt >= 1500 {
				lineOrderLevel = 6
			} else if item.Cnt >= 5500 {
				lineOrderLevel = 5
			} else if item.Cnt >= 3000 {
				lineOrderLevel = 4
			} else if item.Cnt >= 1500 {
				lineOrderLevel = 3
			} else if item.Cnt >= 500 {
				lineOrderLevel = 2
			} else if item.Cnt >= 1 {
				lineOrderLevel = 1
			}
			logList.Items[i].Level = lineOrderLevel
		}
	}

	response.OkData(ctx, logList)
}

// GetUserLogsNew 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/user-logs-new [GET]
func (handler *AccountHandler) GetUserLogsNew(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	logList, logListErr := service.GetUserLogsNew(ctx, operator.Id)
	if logListErr != nil {
		response.Error(ctx, logListErr)
		return
	}
	response.OkData(ctx, logList)
}

// GetUserLogsNewTz 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/user-logs-new-tz [GET]
func (handler *AccountHandler) GetUserLogsNewTz(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	logList, logListErr := service.GetUserLogsNewTz(ctx, operator.Id)
	if logListErr != nil {
		response.Error(ctx, logListErr)
		return
	}
	response.OkData(ctx, logList)
}

// GetGames 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/games [GET]
func (handler *AccountHandler) GetGames(ctx *gin.Context) {

	logList, logListErr := service.GetGames(ctx)
	if logListErr != nil {
		response.Error(ctx, logListErr)
		return
	}
	response.OkData(ctx, logList)
}

// GetGame 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/game [GET]
func (handler *AccountHandler) GetGame(ctx *gin.Context) {

	point, _ := service.EsGetGameXhNum()

	var ccc float64
	db.GetRedisClient().Get(ctx, "gam1:ac").Scan(&ccc)
	pointInt, _ := decimal.NewFromString(point)
	cccccc := decimal.NewFromInt32(int32(ccc))
	response.OkData(ctx, pointInt.Add(cccccc))
}

// GetGameID 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/game/11 [GET]
func (handler *AccountHandler) GetGameID(ctx *gin.Context) {

	var ccc string
	db.GetRedisClient().Get(ctx, "gam3331:ac").Scan(&ccc)

	var ccc2 string
	db.GetRedisClient().Get(ctx, "gam3332:ac").Scan(&ccc2)

	mml := map[string]string{
		"url1": ccc,
		"url2": ccc2,
	}

	response.OkData(ctx, mml)
}

// GetGameIDs 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/gamekllll [GET]
func (handler *AccountHandler) GetGameIDs(ctx *gin.Context) {

	type sss struct {
		Url  string `json:"url"`
		Type int    `json:"type"`
	}

	var req sss
	err := ctx.ShouldBindJSON(&req)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	if req.Type == 1 {
		db.GetRedisClient().Set(ctx, "gam3331:ac", req.Url, 0)
	} else {
		db.GetRedisClient().Set(ctx, "gam3332:ac", req.Url, 0)
	}

	response.Ok(ctx)
}

// GetGameAll 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/game-all [GET]
func (handler *AccountHandler) GetGameAll(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	point, _ := service.EsGetGameXhNum()

	var ccc float64
	db.GetRedisClient().Get(ctx, "gam1:ac").Scan(&ccc)
	pointInt, _ := decimal.NewFromString(point)
	cccccc := decimal.NewFromInt32(int32(ccc))

	nowTime := time.Now().Format("20060102")

	var ccccccToday float64
	db.GetRedisClient().Get(ctx, "gam1:ac:"+nowTime).Scan(&ccccccToday)

	var cccc11my int64
	db.GetDb().Table("my_game_moneys").Debug().Group("game_id").Where("type =1 and days=? and uid=?", nowTime, operator.Id).Count(&cccc11my)

	var sssumMoney []emodel.My_game_day

	db.GetDb().Table("my_game_day").Debug().Select("sum(jl) jl").Where(" uid=?", operator.Id).Find(&sssumMoney)

	//ddd, _ := service.EsUserLogsHistorySelectTzSum(operator.Id, 1)
	var ss float64
	if len(sssumMoney) > 0 {
		ss = sssumMoney[0].Jl
	}

	ccccccTodayStr := strconv.FormatFloat(ccccccToday, 'f', 1, 64)
	ssStr := strconv.FormatFloat(ss, 'f', 5, 64)

	response.OkData(ctx, map[string]interface{}{
		"all":    pointInt.Add(cccccc).Round(2),
		"today":  ccccccTodayStr,
		"zcc_my": cccc11my,
		"leiji":  ssStr,
	})
}

// GetGameMe 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/game-money [GET]
func (handler *AccountHandler) GetGameMe(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	user := emodel.My_user{}
	if err = db.GetDb().Select("money", "point").Where("id=?", operator.Id).First(&user).Error; err != nil {
		response.Error(ctx, err)
		return
	}

	response.OkData(ctx, map[string]any{
		"gameMoney1": user.Money,
		"gameMoney2": user.Point,
		"id":         operator.Id,
		"nickname":   operator.Id,
	})
}

// GetIronElmMe 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/iron-elm/me [GET]
func (handler *AccountHandler) GetIronElmMe(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	user := emodel.My_user{}
	if err = db.GetDb().Select("sl", "tz").Where("id=?", operator.Id).First(&user).Error; err != nil {
		response.Error(ctx, err)
		return
	}

	response.OkData(ctx, map[string]any{
		"feed":     user.Sl,
		"tz":       user.Tz,
		"id":       operator.Id,
		"nickname": operator.Id,
	})
}

// GetIronElmList 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/iron-elm [GET]
func (handler *AccountHandler) GetIronElmList(ctx *gin.Context) {
	req := model.QueryUserLogRequest{}
	if err := ctx.ShouldBindQuery(&req); err != nil {
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	pageInt := req.Page
	if pageInt == 0 {
		pageInt = 1
	}
	query := db.GetDb().Where("uid=? and status<2", operator.Id)
	query = query.Order("level desc,switch desc,id desc")
	newList, _ := dto.Paginate[emodel.My_Tieqiu](query, &dto.PaginatorOption{
		Page:     pageInt,
		PageSize: 15,
	})

	response.OkData(ctx, newList)
}

// GetIronElmListTieqiu 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/iron-elm/{tqid} [GET]
func (handler *AccountHandler) GetIronElmListTieqiu(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	tqid := ctx.Param("tqid")
	tqidInt, _ := strconv.Atoi(tqid)

	query := db.GetDb().Select("id").Where("uid=? and status<2 and tqid=?", operator.Id, tqidInt)

	var tieqiu emodel.My_Tieqiu
	query.Debug().Find(&tieqiu)
	response.OkData(ctx, tieqiu.Id > 0)
}

// GetIronTransactionElmList 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/iron-elm/transaction [GET]
func (handler *AccountHandler) GetIronTransactionElmList(ctx *gin.Context) {
	req := model.QueryUserLogRequest{}
	if err := ctx.ShouldBindQuery(&req); err != nil {
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	pageInt := req.Page
	if pageInt == 0 {
		pageInt = 1
	}
	query := db.GetDb()
	if req.Type == 0 {
		query = query.Where("(uid=? or puid=?)", operator.Id, operator.Id)
	} else if req.Type == 1 {
		query = query.Where("uid=?", operator.Id)
	} else if req.Type == 2 {
		query = query.Where("puid=?", operator.Id)
	}

	query = query.Order("id desc")
	newList, _ := dto.Paginate[emodel.My_order_dea_tieqiu](query, &dto.PaginatorOption{
		Page:     pageInt,
		PageSize: 15,
	})

	response.OkData(ctx, newList)
}

// GetIronOreList 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/iron-ore [GET]
func (handler *AccountHandler) GetIronOreList(ctx *gin.Context) {
	req := model.QueryUserLogRequest{}
	if err := ctx.ShouldBindQuery(&req); err != nil {
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	pageInt := req.Page
	if pageInt == 0 {
		pageInt = 1
	}
	query := db.GetDb().Where("uid=? and num>0", operator.Id)
	query = query.Order("type desc,id desc")
	newList, _ := dto.Paginate[emodel.My_Tiekuang](query, &dto.PaginatorOption{
		Page:     pageInt,
		PageSize: 15,
	})

	response.OkData(ctx, newList)
}

// GetIronOreSell 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/iron-elm/sell [POST]
func (handler *AccountHandler) GetIronOreSell(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	//GameMoney
	var reqData emodel.GameTeiqiu
	if err = ctx.ShouldBindJSON(&reqData); err != nil {
		response.Error(ctx, err)
		return
	}

	if reqData.Num < 1 {
		response.Error(ctx, sferrors.NewStringf("最少1个"))
		return
	}

	//if reqData.Type <= 0 || reqData.Type > 100 {
	//	response.Error(ctx, sferrors.NewStringf("非法操作"))
	//	return
	//}
	var myUser emodel.My_user
	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		txErr := tx.Select("id", "mobile", "sl").Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}

		//var myTiekuang emodel.My_Tiekuang
		//if err = tx.Where("uid=? and type=?", operator.Id, reqData.Type).Select("num", "id").First(&myTiekuang).Error; err != nil {
		//	return sferrors.NewStringf("非法操作")
		//}

		//if myTiekuang.Num <= reqData.Num {
		//	return sferrors.NewStringf("数量不足 剩余" + fmt.Sprintf("%.2f", myTiekuang.Num))
		//}
		s := "黑铁矿"
		dz := 0.001
		if reqData.Type == 1 {
			s = "铁矿"
			dz = 0.002
		} else if reqData.Type == 2 {
			s = "银矿"
			dz = 0.003
		} else if reqData.Type == 3 {
			s = "金矿"
			dz = 0.004
		}
		nums := reqData.Num * float64(dz) * float64(reqData.Quality)
		txErr = service.CreateSlLog(tx, myUser, nums, 12, myUser.Id, fmt.Sprintf("兑换%s石【品质:%d】%d个", s, reqData.Quality, int(reqData.Num)))
		if txErr != nil {
			return txErr
		}

		//if err = tx.Exec("update my_tiekuang set num=num-? where id=? ", math.Abs(nums), myTiekuang.Id).Error; err != nil {
		//	return err
		//}
		txErr = tx.Select("sl", "tz").Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}
		sf_time.SetRedisKey(ctx, "ks_sl", nums)
		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}

	response.OkData(ctx, map[string]any{
		"feed":     myUser.Sl,
		"tz":       myUser.Tz,
		"id":       operator.Id,
		"nickname": operator.Id,
	})
}

// GetIronOreSellAll 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/iron-elm/sell-all [POST]
func (handler *AccountHandler) GetIronOreSellAll(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	//GameMoney
	var reqData []*emodel.GameTeiqiu
	if err = ctx.ShouldBindJSON(&reqData); err != nil {
		response.Error(ctx, err)
		return
	}

	if len(reqData) == 0 {
		response.Error(ctx, sferrors.NewStringf("最少1个"))
		return
	}

	for _, i2 := range reqData {
		if i2.Num < 1 {
			response.Error(ctx, sferrors.NewStringf("最少1个"))
			return
		}
	}

	//if reqData.Type <= 0 || reqData.Type > 100 {
	//	response.Error(ctx, sferrors.NewStringf("非法操作"))
	//	return
	//}
	var myUser emodel.My_user
	var numssss float64
	err = db.GetDb().Transaction(func(tx *gorm.DB) error {
		txErr := tx.Select("id", "mobile", "sl").Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}
		for _, i2 := range reqData {
			s := "黑铁矿"
			dz := 0.001
			if i2.Type == 1 {
				s = "铁矿"
				dz = 0.002
			} else if i2.Type == 2 {
				s = "银矿"
				dz = 0.003
			} else if i2.Type == 3 {
				s = "金矿"
				dz = 0.004
			}
			nums := i2.Num * float64(dz) * float64(i2.Quality)
			numssss += nums
			go task.SendUserMoneyAdd(operator.Id, nums, 12, 1, fmt.Sprintf("兑换%s石【品质:%d】%d个", s, i2.Quality, int(i2.Num)))
		}

		sf_time.SetRedisKey(ctx, "ks_sl", numssss)
		myUser.Sl += numssss
		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}

	response.OkData(ctx, map[string]any{
		"feed":     myUser.Sl,
		"tz":       myUser.Tz,
		"id":       operator.Id,
		"nickname": operator.Id,
	})
}

// GetIronOreSellAllTow 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/iron-elm/sell-all-tow [POST]
func (handler *AccountHandler) GetIronOreSellAllTow(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	//GameMoney
	var reqData emodel.GameTeiqiuArr
	if err = ctx.ShouldBindJSON(&reqData); err != nil {
		response.Error(ctx, err)
		return
	}

	if len(reqData.GameTeiqiuMap) == 0 {
		response.Error(ctx, sferrors.NewStringf("最少1个"))
		return
	}

	for _, i2 := range reqData.GameTeiqiuMap {
		if i2.Num < 1 {
			response.Error(ctx, sferrors.NewStringf("最少1个"))
			return
		}
	}

	//if reqData.Type <= 0 || reqData.Type > 100 {
	//	response.Error(ctx, sferrors.NewStringf("非法操作"))
	//	return
	//}
	var myUser emodel.My_user
	var numssss float64
	err = db.GetDb().Transaction(func(tx *gorm.DB) error {
		txErr := tx.Select("id", "mobile", "sl").Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}
		for _, i2 := range reqData.GameTeiqiuMap {
			s := "黑铁矿"
			dz := 0.001
			if i2.Type == 1 {
				s = "铁矿"
				dz = 0.002
			} else if i2.Type == 2 {
				s = "银矿"
				dz = 0.003
			} else if i2.Type == 3 {
				s = "金矿"
				dz = 0.004
			}
			nums := i2.Num * float64(dz) * float64(i2.Quality)
			numssss += nums
			go task.SendUserMoneyAdd(operator.Id, nums, 12, 1, fmt.Sprintf("兑换%s石【品质:%d】%d个", s, i2.Quality, int(i2.Num)))
		}

		sf_time.SetRedisKey(ctx, "ks_sl", numssss)
		myUser.Sl += numssss
		cache.RedisContextSet(ctx, fmt.Sprintf("%s_%d", reqData.OrderId, operator.Id), true, 3*time.Hour)
		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}

	response.OkData(ctx, map[string]any{
		"feed":     myUser.Sl,
		"tz":       myUser.Tz,
		"id":       operator.Id,
		"nickname": operator.Id,
	})
}

func (handler *AccountHandler) GetSellStatus(ctx *gin.Context) {
	orderId := ctx.Param("orderId")

	if orderId == "" {
		response.Error(ctx, sferrors.NewStringf("orderId is null"))
		return
	}

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	var nowStatus bool
	newStatus, _ := cache.RedisContextGet[bool](ctx, fmt.Sprintf("%s_%d", orderId, operator.Id))
	if newStatus != nil {
		nowStatus = true
	}
	response.OkData(ctx, nowStatus)
}

func (handler *AccountHandler) SendSms(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	aliyun := new(aliyun.SmsService)
	randStr := service.RandomInt(6)
	errs := aliyun.SendRandMsg(operator.Mobile, randStr)
	if errs != nil {
		response.Error(ctx, errs)
		return
	}

	oldPwdH, err := service.Md5PayPwd(randStr + "abcdef")
	if err != nil {
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	cache.RedisContextSet(ctx, "game_yzm_"+operator.Mobile, oldPwdH, 5*time.Minute)

	response.OkData[string](ctx, "获取成功")
}

// SendTieqiu 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/iron-elm/send [POST]
func (handler *AccountHandler) SendTieqiu(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if operator.Y == 1 {
		response.Error(ctx, sferrors.NewString("需要先进行身份认证"))
		return
	}

	var giftMoney model.SengTieqiu
	if err = ctx.ShouldBindJSON(&giftMoney); err != nil {
		response.Error(ctx, err)
		return
	}

	if giftMoney.Name == "" {
		response.Error(ctx, sferrors.NewStringf("请输入对方姓名"))
		return
	}

	//var goldRate int
	//db.GetRedisClient().Get(ctx, "goldRate").Scan(&goldRate)
	//
	if giftMoney.Code != "20180808" {
		err = handler2.CheckYzmTieqiu(ctx, operator.Mobile, giftMoney.Code)
		if err != nil {
			response.Error(ctx, sferrors.NewString("验证码错误"))
			return
		}
	}

	//operator
	if operator.C > 0 {
		//订单
		var zzhuanCount int64
		db.GetDb().Debug().Table("my_order_dea_tieqiu").Where("flag < 2 and uid =? and create_time >= ? ", operator.Id, time.Now().Format("2006-01-02")+" 00:00:00").Count(&zzhuanCount)
		if zzhuanCount >= int64(operator.C) {
			response.Error(ctx, sferrors.NewStringf("转赠次数已用完"))
			return
		}
	}
	//if operator.Zz == 0 {
	var zhuanCount int64
	db.GetDb().Debug().Table("my_order_dea_tieqiu").Where("flag < 2 and uid =? and create_time >= ? ", operator.Id, time.Now().Format("2006-01-02")+" 00:00:00").Count(&zhuanCount)
	if zhuanCount >= 5 {
		response.Error(ctx, sferrors.NewStringf("一天最多转五次"))
		return
	}
	//}

	pUser, err := dto.GetSysUserDetailById(giftMoney.Puid)
	if err != nil || pUser == nil {
		response.Error(ctx, sferrors.NewStringf("请输入正确的对方用户id"))
		return
	}
	if giftMoney.Name != pUser.DyName {
		response.Error(ctx, sferrors.NewStringf("对方姓名校验失败"))
		return
	}
	if pUser.Id == operator.Id {
		response.Error(ctx, sferrors.NewStringf("不能自己转自己"))
		return
	}

	var tieQiue emodel.My_Tieqiu
	if err = db.GetDb().Select("id", "status", "tqid").Where("uid=? and tqid=? and status<2", operator.Id, giftMoney.ID).First(&tieQiue).Error; err != nil {
		response.Error(ctx, sferrors.NewStringf("非法操作801"))
		return
	}
	if tieQiue.Id == 0 {
		response.Error(ctx, sferrors.NewStringf("非法操作802"))
		return
	}
	if tieQiue.Status != 0 {
		response.Error(ctx, sferrors.NewStringf("非法操作"))
		return
	}
	newData := emodel.My_order_dea_tieqiu{
		Uid:     operator.Id,
		Puid:    pUser.Id,
		Pid:     tieQiue.Id,
		Tqid:    tieQiue.Tqid,
		Pmobile: pUser.Mobile,
		Mobile:  operator.Mobile,
	}
	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		txErr := tx.Omit("create_time", "qr_time").Create(&newData).Error
		if txErr != nil {
			return txErr
		}
		txErr = tx.Table(tieQiue.TableName()).Where("id=?", tieQiue.Id).UpdateColumn("status", 1).Error
		if txErr != nil {
			return txErr
		}

		//txErr = tx.Set("gorm:query_option", "FOR UPDATE").First(&pUser, pUser.Id).Error
		//if txErr != nil {
		//	return txErr
		//}
		//txErr = service.CreateUserLog(tx, &pUser.My_user, giftMoney.Num, 1, myUser.Id, "收到 "+fmt.Sprintf("%d", myUser.Id)+" 的转赠")
		//if txErr != nil {
		//	return txErr
		//}
		//if txErr = service.CreateUserPointLog(tx, &pUser.My_user, giftMoney.Num*100, 1, myUser.Id, "收到 "+fmt.Sprintf("%d", myUser.Id)+" 的转赠"); txErr != nil {
		//	return txErr
		//}

		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData(ctx, newData.Id)
}

// SendTieqiuConfirm 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/iron-elm/confirm [POST]
func (handler *AccountHandler) SendTieqiuConfirm(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if operator.Y == 1 {
		response.Error(ctx, sferrors.NewString("需要先进行身份认证"))
		return
	}

	var giftMoney model.SengTieqiuConfirm
	if err = ctx.ShouldBindJSON(&giftMoney); err != nil {
		response.Error(ctx, err)
		return
	}

	if giftMoney.ID <= 0 {
		response.Error(ctx, sferrors.NewStringf("id错误"))
		return
	}

	var tieQiue emodel.My_order_dea_tieqiu
	if err = db.GetDb().Debug().Select("id", "flag", "puid", "pid").Where("uid=? and flag=0  and id=?", operator.Id, giftMoney.ID).First(&tieQiue).Error; err != nil {
		response.Error(ctx, err)
		return
	}
	if tieQiue.Id == 0 {
		response.Error(ctx, sferrors.NewStringf("非法操作802"))
		return
	}
	if tieQiue.Flag != 0 {
		response.Error(ctx, sferrors.NewStringf("只有申请中才能操作"))
		return
	}

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		txErr := tx.Table(tieQiue.TableName()).Where("id=?", tieQiue.Id).UpdateColumns(map[string]interface{}{
			"flag":    1,
			"qr_time": time.Now().Format("2006-01-02 15:04:05"),
		}).Error
		if txErr != nil {
			return txErr
		}
		var mysss emodel.My_Tieqiu
		if err = tx.Where("id=? and uid=? and status<2", tieQiue.Pid, operator.Id).First(&mysss).Error; err != nil {
			return err
		}
		if mysss.Id == 0 {
			return sferrors.NewStringf("no found")
		}
		txErr = tx.Table(new(emodel.My_Tieqiu).TableName()).Where("id=?", tieQiue.Pid).UpdateColumns(map[string]interface{}{
			"status": 2,
		}).Error
		if txErr != nil {
			return txErr
		}

		newData := emodel.My_Tieqiu{
			Uid:  tieQiue.Puid,
			Type: mysss.Type,
			Cl:   mysss.Cl,
			Tqid: mysss.Tqid,
		}
		if err = tx.Omit("create_time").Create(&newData).Error; err != nil {
			return err
		}

		//txErr = tx.Set("gorm:query_option", "FOR UPDATE").First(&pUser, pUser.Id).Error
		//if txErr != nil {
		//	return txErr
		//}
		//txErr = service.CreateUserLog(tx, &pUser.My_user, giftMoney.Num, 1, myUser.Id, "收到 "+fmt.Sprintf("%d", myUser.Id)+" 的转赠")
		//if txErr != nil {
		//	return txErr
		//}
		//if txErr = service.CreateUserPointLog(tx, &pUser.My_user, giftMoney.Num*100, 1, myUser.Id, "收到 "+fmt.Sprintf("%d", myUser.Id)+" 的转赠"); txErr != nil {
		//	return txErr
		//}

		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData[string](ctx, "操作成功")
}

// GetIronElmSwitch 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/iron-elm [PUT]
func (handler *AccountHandler) GetIronElmSwitch(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	var reqData emodel.GameTeiqiuSwitch
	if err = ctx.ShouldBindJSON(&reqData); err != nil {
		response.Error(ctx, err)
		return
	}
	if reqData.Type != 1 {
		reqData.Type = 0
	}

	idInt := reqData.ID
	var tieqiu *emodel.My_Tieqiu
	if err = db.GetDb().Where("id=? and uid=?", idInt, operator.Id).First(&tieqiu).Error; err != nil {
		response.Error(ctx, sferrors.NewString("未找到"))
		return
	}
	if reqData.Type == 1 {
		db.GetDb().Table(tieqiu.TableName()).Where("uid=?", idInt, operator.Id).UpdateColumn("swicth", 0)
		db.GetDb().Table(tieqiu.TableName()).Where("id=?", idInt).UpdateColumn("switch", 1)
	} else {
		db.GetDb().Table(tieqiu.TableName()).Where("id=?", idInt).UpdateColumn("switch", 0)
	}
	response.OkData(ctx, "操作成功")

}

// GetIronElmLevel 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/iron-elm/level [POST]
func (handler *AccountHandler) GetIronElmLevel(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	//GameMoney
	var reqData emodel.GameLevel
	if err = ctx.ShouldBindJSON(&reqData); err != nil {
		response.Error(ctx, err)
		return
	}

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {
		var tieqiu *emodel.My_Tieqiu
		if err = db.GetDb().Select("id").Where("tqid=? and uid=?", reqData.ID, operator.Id).First(&tieqiu).Error; err != nil {
			return err
		}
		if tieqiu.Id <= 0 {
			return sferrors.NewStringf("未找到记录")
		}

		newData := emodel.My_TieqiuLevel{
			Uid:   operator.Id,
			Level: reqData.LevelNum,
			Num:   reqData.Num,
			Tid:   tieqiu.Id,
			Demo:  reqData.Mode,
		}
		if err = tx.Omit("create_time").Create(&newData).Error; err != nil {
			return err
		}

		if err = tx.Table(tieqiu.TableName()).Where("id=?", tieqiu.Id).UpdateColumn("level", reqData.LevelNum).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData(ctx, "Success")
}

// GetIronElmBuy 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/iron-elm/buy [POST]
func (handler *AccountHandler) GetIronElmBuy(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	//GameMoney
	var reqData emodel.GameTeiqiu
	if err = ctx.ShouldBindJSON(&reqData); err != nil {
		response.Error(ctx, err)
		return
	}

	//if reqData.Num <= 1 {
	//	response.Error(ctx, sferrors.NewStringf("最少1个"))
	//	return
	//}
	if reqData.Type != 0 && reqData.Type != 1 && reqData.Type != 2 {
		response.Error(ctx, sferrors.NewStringf("非法操作"))
		return
	}

	//暂定数量呢？5 10 15
	needNun := 1000
	cl := 1
	var flag int
	s := ""
	switch reqData.Type {
	case 0:
		needNun = 5
		cl = 1
		flag = 57
	case 1:
		needNun = 10
		flag = 58
		cl = 2
		s = "银"
	case 2:
		needNun = 15
		cl = 3
		flag = 59
		s = "金"
	}
	var myUser emodel.My_user
	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		txErr := tx.Select("id", "mobile", "tz").Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}
		if myUser.Tz < float64(needNun) {
			return sferrors.NewStringf("可扣除通用积分不足")
		}

		newData := emodel.My_Tieqiu{
			Uid:  operator.Id,
			Type: reqData.Type,
			Cl:   float64(cl),
			Tqid: reqData.Tqid,
		}
		if err = tx.Omit("create_time").Create(&newData).Error; err != nil {
			return err
		}
		//扣除
		txErr = service.CreateTzLog(tx, myUser, float64(needNun), flag, myUser.Id, "抢购 "+s+"铁楸")
		if txErr != nil {
			return txErr
		}
		txErr = tx.Select("id", "sl", "tz").Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}
		return nil
	})

	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData(ctx, map[string]any{
		"feed":     myUser.Sl,
		"tz":       myUser.Tz,
		"id":       operator.Id,
		"nickname": operator.Id,
	})
}

// GetGameMeNew 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/game-money-new [GET]
func (handler *AccountHandler) GetGameMeNew(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	user := emodel.My_user{}
	if err = db.GetDb().Select("money", "point", "tz", "tz1", "tz2", "tz3", "tz4").Where("id=?", operator.Id).First(&user).Error; err != nil {
		response.Error(ctx, err)
		return
	}

	response.OkData(ctx, map[string]any{
		"id":    operator.Id,
		"money": user.Money,
		"point": user.Point,
		"tz":    operator.Tz,
		"tz1":   operator.Tz1,
		"tz2":   operator.Tz2,
		"tz3":   operator.Tz3,
		"tz4":   operator.Tz4,
	})
}

// GetGameMoney 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/game-money [POST]
func (handler *AccountHandler) GetGameMoney(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	//GameMoney
	var reqData emodel.GameMoney
	if err = ctx.ShouldBindJSON(&reqData); err != nil {
		response.Error(ctx, err)
		return
	}
	if reqData.Num <= 1 {
		response.Error(ctx, sferrors.NewStringf("最少1个"))
		return
	}
	if reqData.Type == 2 {
		response.Error(ctx, sferrors.NewStringf("已废弃"))
		return
	}
	nowTime := time.Now().Format("20060102")
	daysIndex, _ := strconv.Atoi(nowTime)

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		var myUser emodel.My_user
		txErr := tx.Select("id", "mobile", "money", "point", "sl").Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}

		////如果是第这局第一次参加 那么赠送0.1个私聊
		var countFlag int64
		db.GetDb().Table("my_game_moneys").Where("uid=? and game_id=? and game_type=?", operator.Id, reqData.GameId, reqData.GameType).Count(&countFlag)

		if countFlag == 0 {
			txErr = service.CreateSlLog(tx, myUser, 0.1, 5, myUser.Id, "参加游戏")
			if txErr != nil {
				return txErr
			}
		}
		newData := emodel.My_GameMoney{
			Uid:      operator.Id,
			Mobile:   operator.Mobile,
			Num:      reqData.Num,
			Type:     reqData.Type,
			GameType: reqData.GameType,
			Mode:     "参与游戏",
			GameId:   reqData.GameId,
			Days:     daysIndex,
		}
		if err = tx.Create(&newData).Error; err != nil {
			return err
		}

		switch reqData.GameType {
		case 1:
			if myUser.Money < reqData.Num {
				return sferrors.NewStringf("可扣除通用积分不足")
			}

			//扣除
			txErr = service.CreateUserLog(tx, myUser, reqData.Num, 2, myUser.Id, "参加游戏")
			if txErr != nil {
				return txErr
			}

		case 2:
			if myUser.Point < reqData.Num {
				return sferrors.NewStringf("可扣除贡献不足")
			}
			//扣除
			txErr = service.CreateUserPointLog(tx, myUser, reqData.Num, 12, myUser.Id, "参加游戏")
			if txErr != nil {
				return txErr
			}

		}

		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData(ctx, "Success")
}

// GetGameMoneyTow 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/join-game [POST]
func (handler *AccountHandler) GetGameMoneyTow(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	type DecBalanceReq struct {
		CoinType     string  `json:"coinType"`
		GameName     string  `json:"gameName"`
		ChangePoints float64 `json:"changePoints"`
		BatchNo      int     `json:"batch_no"`
		RoomId       int8    `json:"roomId"`
	}
	//GameMoney
	var reqData DecBalanceReq
	if err = ctx.ShouldBindJSON(&reqData); err != nil {
		response.Error(ctx, err)
		return
	}

	if reqData.BatchNo == 0 {
		response.Error(ctx, sferrors.NewStringf("该游戏已有结算，请勿重复提交"))
		return
	}
	var kaiguan int
	db.GetRedisClient().Get(ctx, "qdz2").Scan(&kaiguan)
	if kaiguan == 1 {
		response.Error(ctx, sferrors.NewStringf("暂时关闭"))
		return
	}

	if reqData.ChangePoints < 0.1 {
		response.Error(ctx, sferrors.NewStringf("最少0.1个"))
		return
	}
	if reqData.ChangePoints > 20 {
		response.Error(ctx, sferrors.NewStringf("最多20个"))
		return
	}
	//5个小时内 这个游戏这个人 不能超过10个
	var yt float64
	redKey := fmt.Sprintf("game_money_tow_%d_%d_nnn_1", operator.Id, reqData.BatchNo)
	db.GetRedisClient().Get(ctx, redKey).Scan(&yt)
	ccc := math.Round((yt+reqData.ChangePoints)*10) / 10
	if ccc > 20 {
		fmt.Println(ccc)
		response.Error(ctx, sferrors.NewStringf("单局游戏总投注不能超过20个"))
		return
	}

	db.GetRedisClient().Set(ctx, redKey, ccc, 5*time.Hour)

	nowTime := time.Now().Format("20060102")
	daysIndex, _ := strconv.Atoi(nowTime)
	var myUser emodel.My_user
	ssss, _ := cache.RedisContextGet[float64](ctx, "ssssss")
	mmsss := *ssss
	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		txErr := tx.Select("tz", "id", "mobile", "money").Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}

		////如果是第这局第一次参加 那么赠送0.1个私聊

		//if countFlag == 0 {
		//	txErr = service.CreateSlLog(tx, myUser, 0.1, 5, myUser.Id, "参加游戏")
		//	if txErr != nil {
		//		return txErr
		//	}
		//}
		gmeId := strconv.Itoa(reqData.BatchNo)
		newData := emodel.My_GameMoneyTow{
			Uid:      operator.Id,
			Mobile:   operator.Mobile,
			Num:      reqData.ChangePoints,
			Type:     1,
			GameType: 1,
			Mode:     "参与抢地主",
			GameId:   gmeId,
			Days:     daysIndex,
			RoomId:   reqData.RoomId,
		}
		if err = tx.Create(&newData).Error; err != nil {
			return err
		}

		if myUser.Tz < reqData.ChangePoints {
			return sferrors.NewStringf("可扣除通证不足")
		}

		//扣除
		txErr = service.CreateTzLog(tx, myUser, reqData.ChangePoints, 54, myUser.Id, "参加抢地主 "+gmeId)
		if txErr != nil {
			return txErr
		}

		//增加私聊
		txErr = service.CreateSlLog(tx, myUser, reqData.ChangePoints*mmsss, 8, myUser.Id, "参加抢地主 "+gmeId)
		if txErr != nil {
			return txErr
		}
		myUser.Tz -= reqData.ChangePoints

		//sf_time.SetRedisKey(ctx, "dz_tz", reqData.ChangePoints)
		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}
	type RespType struct {
		UserId uint64  `json:"userId"`
		Food   float64 `json:"food"`
	}

	userIdStr := strconv.Itoa(int(operator.Id))

	response.OkData(ctx, map[string]interface{}{
		"coin":     myUser.Money,
		"food":     myUser.Tz,
		"userId":   userIdStr,
		"nickName": operator.Nickname,
		"avatar":   "",
	})
	return
}

// GetGameMoneyTowSl 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/join-game-sl [POST]
func (handler *AccountHandler) GetGameMoneyTowSl(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	type DecBalanceReq struct {
		CoinType     string  `json:"coinType"`
		GameName     string  `json:"gameName"`
		ChangePoints float64 `json:"changePoints"`
		BatchNo      int     `json:"batch_no"`
		RoomId       int8    `json:"roomId"`
	}
	//GameMoney
	var reqData DecBalanceReq
	if err = ctx.ShouldBindJSON(&reqData); err != nil {
		response.Error(ctx, err)
		return
	}

	if reqData.BatchNo == 0 {
		response.Error(ctx, sferrors.NewStringf("该游戏已有结算，请勿重复提交"))
		return
	}
	var kaiguan int
	db.GetRedisClient().Get(ctx, "qdz2-sl").Scan(&kaiguan)
	if kaiguan == 1 {
		response.Error(ctx, sferrors.NewStringf("暂时关闭"))
		return
	}

	if reqData.ChangePoints < 1 {
		response.Error(ctx, sferrors.NewStringf("最少1个"))
		return
	}
	if reqData.ChangePoints > 10000 {
		response.Error(ctx, sferrors.NewStringf("最多10000个"))
		return
	}
	//5个小时内 这个游戏这个人 不能超过10个
	var yt float64
	redKey := fmt.Sprintf("game_money_tow_%d_%d_nnn_1_sl", operator.Id, reqData.BatchNo)
	db.GetRedisClient().Get(ctx, redKey).Scan(&yt)
	ccc := math.Round((yt+reqData.ChangePoints)*10) / 10
	if ccc > 100000 {
		fmt.Println(ccc)
		response.Error(ctx, sferrors.NewStringf("单局游戏总投注不能超过10000个"))
		return
	}

	db.GetRedisClient().Set(ctx, redKey, ccc, 5*time.Hour)

	nowTime := time.Now().Format("20060102")
	daysIndex, _ := strconv.Atoi(nowTime)
	var myUser emodel.My_user
	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		txErr := tx.Select("sl", "id", "mobile", "money").Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}

		////如果是第这局第一次参加 那么赠送0.1个私聊

		//if countFlag == 0 {
		//	txErr = service.CreateSlLog(tx, myUser, 0.1, 5, myUser.Id, "参加游戏")
		//	if txErr != nil {
		//		return txErr
		//	}
		//}
		gmeId := strconv.Itoa(reqData.BatchNo)
		newData := emodel.My_GameMoneyTowSl{
			Uid:      operator.Id,
			Mobile:   operator.Mobile,
			Num:      reqData.ChangePoints,
			Type:     1,
			GameType: 1,
			Mode:     "参与抢地主[饲料]",
			GameId:   gmeId,
			Days:     daysIndex,
			RoomId:   reqData.RoomId,
		}
		if err = tx.Create(&newData).Error; err != nil {
			return err
		}

		if myUser.Sl < reqData.ChangePoints {
			return sferrors.NewStringf("可扣除饲料不足")
		}

		//扣除
		txErr = service.CreateSlLog(tx, myUser, reqData.ChangePoints, 10, myUser.Id, "参加抢地主[饲料] "+gmeId)
		if txErr != nil {
			return txErr
		}
		myUser.Sl -= reqData.ChangePoints

		//sf_time.SetRedisKey(ctx, "sl_sl", reqData.ChangePoints)
		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}
	type RespType struct {
		UserId uint64  `json:"userId"`
		Food   float64 `json:"food"`
	}

	userIdStr := strconv.Itoa(int(operator.Id))

	response.OkData(ctx, map[string]interface{}{
		"coin":     myUser.Sl,
		"food":     myUser.Sl,
		"userId":   userIdStr,
		"nickName": operator.Nickname,
		"avatar":   "",
	})
	return
}

// GetGameMoneyPoint 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/game-money-point [POST]
func (handler *AccountHandler) GetGameMoneyPoint(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	//GameMoney
	var reqData emodel.GameMoneyPoint
	if err = ctx.ShouldBindJSON(&reqData); err != nil {
		response.Error(ctx, err)
		return
	}

	if reqData.Num != 100 && reqData.Num != 1000 {
		response.Error(ctx, sferrors.NewStringf("数量不对"))
		return
	}

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		var myUser emodel.My_user
		txErr := tx.Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}

		if myUser.Money < reqData.Num {
			return sferrors.NewStringf("可扣除通用积分不足")
		}

		if myUser.Point < reqData.Num*100 {
			return sferrors.NewStringf("可扣除贡献不足")
		}

		t := time.Now()
		newData := emodel.My_GamePoints{
			Uid:        operator.Id,
			Mobile:     operator.Mobile,
			Mode:       reqData.GameId,
			CreateTime: &t,
		}
		newData.GameType = 2
		if reqData.Num == 100 {
			newData.GameType = 1
		}

		if err = tx.Create(&newData).Error; err != nil {
			return err
		}

		//扣除
		txErr = service.CreateUserLog(tx, myUser, reqData.Num, 45, myUser.Id, reqData.Mode)
		if txErr != nil {
			return txErr
		}

		//扣除
		txErr = service.CreateUserPointLog(tx, myUser, reqData.Num*100, 39, myUser.Id, reqData.Mode)
		if txErr != nil {
			return txErr
		}

		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}

	user := emodel.My_user{}
	if err = db.GetDb().Select("money", "point", "tz", "tz1", "tz2", "tz3", "tz4").Where("id=?", operator.Id).First(&user).Error; err != nil {
		response.Error(ctx, err)
		return
	}

	response.OkData(ctx, map[string]any{
		"id":    operator.Id,
		"money": user.Money,
		"point": user.Point,
		"tz":    operator.Tz,
		"tz1":   operator.Tz1,
		"tz2":   operator.Tz2,
		"tz3":   operator.Tz3,
		"tz4":   operator.Tz4,
	})
	return
}

// GetGameMoneyTz 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/game-money-tz [POST]
func (handler *AccountHandler) GetGameMoneyTz(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	//GameMoney
	var reqData emodel.GameMoneyTzReq
	if err = ctx.ShouldBindJSON(&reqData); err != nil {
		response.Error(ctx, err)
		return
	}
	if reqData.GameType < 0 || reqData.GameType > 2 {
		response.Error(ctx, sferrors.NewStringf("场次不对"))
		return
	}
	nowTime := time.Now().Format("20060102")
	nowTimeInt, _ := strconv.Atoi(nowTime)
	var myGame emodel.MyGamePk
	db.GetDb().Where("uid=? and days=? and game_type=?", operator.Id, nowTimeInt, reqData.GameType).First(&myGame)

	if myGame.Id > 0 {
		response.Error(ctx, sferrors.NewStringf("今天已经参加过了"))
		return
	}
	var money float64
	moneyType := getMoneyType()

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {
		var myUser emodel.My_user
		txErr := tx.Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}

		//获得币种

		mdoeStr := "初级场"
		//计算获得多钱
		switch reqData.GameType {
		case 0:
			//计算
			jisuan := IsIncentive(60)
			if jisuan {
				generator := sf_time.NewFloatGenerator(0.1, 0.5, 1)
				// 生成10个随机值
				moneys := generator.GenerateMultiple(1)
				money = moneys[0]
			} else {
				generator := sf_time.NewFloatGenerator(0.6, 1, 1)
				// 生成10个随机值
				moneys := generator.GenerateMultiple(1)
				money = moneys[0]
			}
		case 1:
			mdoeStr = "中级场"
			jisuan := IsIncentive(70)
			if jisuan {
				generator := sf_time.NewFloatGenerator(0.5, 2.5, 1)
				// 生成10个随机值
				moneys := generator.GenerateMultiple(1)
				money = moneys[0]
			} else {
				generator := sf_time.NewFloatGenerator(2.5, 5, 1)
				// 生成10个随机值
				moneys := generator.GenerateMultiple(1)
				money = moneys[0]
			}
		case 2:
			mdoeStr = "高级场"
			jisuan := IsIncentive(99)
			if jisuan {
				generator := sf_time.NewFloatGenerator(2.5, 5, 1)
				// 生成10个随机值
				moneys := generator.GenerateMultiple(1)
				money = moneys[0]
			} else {
				generator := sf_time.NewFloatGenerator(5, 25, 1)
				// 生成10个随机值
				moneys := generator.GenerateMultiple(1)
				money = moneys[0]
			}
		}

		t := time.Now()
		newData := emodel.MyGamePk{
			Uid:        operator.Id,
			Mobile:     operator.Mobile,
			GameType:   reqData.GameType,
			Money:      money,
			MoneyType:  moneyType,
			CreateTime: &t,
			Days:       nowTimeInt,
		}

		if err = tx.Create(&newData).Error; err != nil {
			return err
		}

		switch moneyType {
		case 0:
		}

		//扣除
		txErr = service.CreateUserLogAll(tx, moneyType, myUser, money, 999999, myUser.Id, "参加PK获胜【"+mdoeStr+"】")
		if txErr != nil {
			return txErr
		}
		return nil

	})
	if err != nil {
		response.Error(ctx, err)
		return
	}
	ss := emodel.GameMoneyTzResp{
		MoneyType: moneyType,
		Money:     money,
	}

	response.OkData(ctx, ss)
}

// GetGameMoneyWeeks 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/game-money-tz [POST]
func (handler *AccountHandler) GetGameMoneyWeeks(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	qDayMax := time.Now().Unix() - 1757865600
	qDay := int(math.Ceil(float64(qDayMax / 86400 / 7)))

	//GameMoney
	var reqData emodel.GameMoneyWeekReq
	if err = ctx.ShouldBindJSON(&reqData); err != nil {
		response.Error(ctx, err)
		return
	}
	//首
	//先 获取上次自己爬的层数
	if reqData.GameId > 100 || reqData.GameId < 1 {
		response.Error(ctx, sferrors.NewStringf("错误"))
		return
	}

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		var myGame emodel.MyGameWeeks
		tx.Where("uid=? and q=?", operator.Id, qDay).First(&myGame)
		if myGame.L >= reqData.GameId {
			return errors.New("本周已经参加过了")
		}

		if myGame.Id == 0 {
			myGame.Uid = operator.Id
			if err = tx.Omit("id").Create(&myGame).Error; err != nil {
				return err
			}
		}
		starLevel := myGame.L

		var myUser emodel.My_user
		txErr := tx.Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}
		for i := 1; i <= reqData.GameId-starLevel; i++ {
			nowLevel := starLevel + i
			money := weekMiney(nowLevel - 1)
			// 在这里执行你的循环逻辑
			if txErr = service.CreateTzLog(tx, myUser, money, 37, myUser.Id, fmt.Sprintf("参加第%d层通天塔 获得", nowLevel)); txErr != nil {
				return txErr
			}
			myUser.Tz += money
			myGame.Yl += money
		}
		myGame.Weeks = int(time.Now().Weekday())
		myGame.Days, _ = strconv.Atoi(time.Now().Format("20060102"))
		myGame.L = reqData.GameId
		myGame.Q = int(qDay)
		if err = tx.Updates(&myGame).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}

	response.Ok(ctx)
}

func weekMiney(l int) float64 {
	values := []float64{
		0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5,
		0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1,
		1.05, 1.1, 1.15, 1.2, 1.25, 1.3, 1.35, 1.4, 1.45, 1.5,
		1.55, 1.6, 1.65, 1.7, 1.75, 1.8, 1.85, 1.9, 1.95, 2,
		2.05, 2.1, 2.15, 2.2, 2.25, 2.3, 2.35, 2.4, 2.45, 2.5,
		2.55, 2.6, 2.65, 2.7, 2.75, 2.8, 2.85, 2.9, 2.95, 3,
		3.05, 3.1, 3.15, 3.2, 3.25, 3.3, 3.35, 3.4, 3.45, 3.5,
		3.55, 3.6, 3.65, 3.7, 3.75, 3.8, 3.85, 3.9, 3.95, 4,
		4.05, 4.1, 4.15, 4.2, 4.25, 4.3, 4.35, 4.4, 4.45, 4.5,
		4.55, 4.6, 4.65, 4.7, 4.75, 4.8, 4.85, 4.9, 4.95, 5,
	}
	return values[l]
}

func IsIncentive(num int) bool {
	rand.Seed(time.Now().UnixNano())
	return rand.Intn(100) < num // 0-89为true，90-99为false
}

func getMoneyType() int {
	// 定义概率分布：moneyType -> 概率百分比
	probabilities := []int{
		0: 10, // moneyType=0: 40%
		1: 25, // moneyType=1: 15%
		2: 25, // moneyType=2: 15%
		3: 20, // moneyType=3: 15%
		4: 20, // moneyType=4: 15%
	}

	// 计算总权重
	totalWeight := 0
	for _, weight := range probabilities {
		totalWeight += weight
	}

	// 生成随机数
	rand.Seed(time.Now().UnixNano())
	randomNum := rand.Intn(totalWeight)

	// 根据权重选择 moneyType
	cumulativeWeight := 0
	for moneyType, weight := range probabilities {
		cumulativeWeight += weight
		if randomNum < cumulativeWeight {
			return moneyType
		}
	}

	return 0 // 默认返回0
}

// GetNotice 系统公告
// @Summary		系统公告
// @Description	系统公告
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/notice [GET]
func (handler *AccountHandler) GetNotice(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	logList, logListErr := service.GetNoticeLogs(ctx, operator.Id)
	if logListErr != nil {
		response.Error(ctx, logListErr)
		return
	}
	response.OkData[*dto.PaginationList[emodel.My_notice]](ctx, logList)
}

// GetNoticeDetail 系统公告详情
// @Summary		系统公告详情
// @Description	系统公告详情
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/notice/{id} [GET]
func (handler *AccountHandler) GetNoticeDetail(ctx *gin.Context) {
	id := ctx.Param("id")
	if id == "" {
		response.Error(ctx, sferrors.NewString("系统错误"))
		return
	}
	logDea, logListErr := dto.GetNoticeById(id)
	if logListErr != nil {
		response.Error(ctx, logListErr)
		return
	}
	response.OkData(ctx, logDea)
}

// GetMyChild 礼包
// @Summary		礼包
// @Description	礼包
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/myChild/{type}/{PAGE}/{sn} [GET]
func (handler *AccountHandler) GetMyChild(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	types := ctx.Param("type")
	page := ctx.Param("page")
	pageInt, err := strconv.Atoi(page)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if pageInt == 0 {
		pageInt = 1
	}

	sn := ctx.Param("sn")
	query := db.GetDb()

	if sn != "" {
		query = query.Where("mobile=? and (ppid=? or pid=?)", sn, operator.Id, operator.Id)
	} else {
		if types == "0" {
			query = query.Where("pid", operator.Id)
		}
		if types == "1" {
			query = query.Where("ppid", operator.Id)
		}
	}

	query = query.Select("mobile", "bio", "id", "is_task", "nickname", "level", "dy_ture", "create_time")
	query = query.Order("is_task desc,id desc")
	list, err := dto.Paginate[emodel.My_user](query, &dto.PaginatorOption{
		Page:     pageInt,
		PageSize: 8,
	})

	for i, item := range list.Items {
		list.Items[i].Beizhu = getbeizhu(fmt.Sprintf("bz_%d%d", operator.Id, item.Id))
	}

	if err != nil {
		log.Errorf("获取账单记录失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	newList := service.HandleTask(list)
	response.OkData(ctx, newList)
}

// WGetMyChild 礼包
// @Summary		礼包
// @Description	礼包
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/wmyChild/{type}{sn} [GET]
func (handler *AccountHandler) WGetMyChild(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	types := ctx.Param("type")
	page := ctx.Param("page")
	pageInt, err := strconv.Atoi(page)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if pageInt == 0 {
		pageInt = 1
	}

	sn := ctx.Param("sn")
	query := db.GetDb()

	if sn != "" {
		query = query.Where("mobile=? and (w_pid=? or w_ppid=?)", sn, operator.Id, operator.Id)
	} else {
		if types == "0" {
			query = query.Where("w_pid", operator.Id)
		}
		if types == "1" {
			query = query.Where("w_ppid", operator.Id)
		}
	}

	query = query.Select("mobile", "w_level", "bio", "id", "is_task", "nickname", "level", "dy_ture", "create_time")
	query = query.Order("id desc")
	list, err := dto.Paginate[emodel.My_user](query, &dto.PaginatorOption{
		Page:     pageInt,
		PageSize: 8,
	})

	for i, item := range list.Items {
		list.Items[i].Beizhu = getbeizhu(fmt.Sprintf("bz_%d%d", operator.Id, item.Id))
		list.Items[i].Y = getOrderDeaNum(item.Id)
		list.Items[i].WLevel = WlevelHanddel(item.WLevel)
	}

	if err != nil {
		log.Errorf("获取账单记录失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	newList := service.HandleTask(list)
	response.OkData(ctx, newList)
}

// WGetMyChildTow 礼包
// @Summary		礼包
// @Description	礼包
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/wmyChild-tow/{type}{sn} [GET]
func (handler *AccountHandler) WGetMyChildTow(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	types := ctx.Param("type")
	page := ctx.Param("page")
	pageInt, err := strconv.Atoi(page)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if pageInt == 0 {
		pageInt = 1
	}

	sn := ctx.Param("sn")
	query := db.GetDb()
	ids := []string{}
	if sn != "" {
		query = query.Where("mobile=? and (w_pid=? or w_ppid=?)", sn, operator.Id, operator.Id)
	} else {
		if types == "0" {
			query = query.Where("w_pid", operator.Id)
		}
		if types == "1" {

			idssMpa := make([]map[string]interface{}, 0)
			querys := db.GetDb().Table("my_order_w").Select("sum(money)cnt")
			err = querys.Debug().Select("uid").Where("(status =0 or status =4) and( w_ppid=? or w_pid=?)", operator.Id, operator.Id).Group("uid").Find(&idssMpa).Error

			if len(idssMpa) > 0 {
				for _, m := range idssMpa {

					ids = append(ids, strconv.Itoa(int(m["uid"].(int64))))
				}
			} else {
				ids = append(ids, "0")
			}
			query.Where("id in (?)", ids)
		}
		if types == "2" {
			query = query.Where("w_ppid", operator.Id)
		}
	}

	query = query.Select("mobile", "w_pid", "w_ppid", "w_level", "bio", "id", "is_task", "nickname", "level", "dy_ture", "create_time")
	query = query.Debug().Order("id desc")
	if types == "1" {
		query = query.Where("id in(?)", ids)
	}

	list, err := dto.Paginate[emodel.My_user](query, &dto.PaginatorOption{
		Page:     pageInt,
		PageSize: 8,
		ShowSQL:  true,
	})
	if err != nil {
		log.Errorf("获取账单记录失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	if list == nil {
		response.Ok(ctx)
		return
	}

	for i, item := range list.Items {
		list.Items[i].Beizhu = getbeizhu(fmt.Sprintf("bz_%d%d", operator.Id, item.Id))
		list.Items[i].Y = getOrderDeaNum(item.Id)
		list.Items[i].WLevel = WlevelHanddel(item.WLevel)
	}

	newList := service.HandleTask(list)
	response.OkData(ctx, newList)
}

func getbeizhu(lookKey string) string {
	newStr, err := cache.RedisContextGet[string](context.TODO(), lookKey)
	if err == nil && newStr != nil {
		return *newStr
	}
	return ""
}

func getOrderDeaNum(id uint64) int64 {

	query := db.GetDb().Table("my_order_w").Select("sum(money)cnt")
	query = query.Debug().Where("status=1 and uid=?", id)
	type cnt struct {
		Cnt float64 `json:"cnt"`
	}
	ccc := make([]cnt, 0)
	query = query.Debug().Find(&ccc)
	var mmm float64
	if len(ccc) > 0 {
		mmm = ccc[0].Cnt
	}
	return int64(mmm)
}

func IsSubordinateRecursive(db *gorm.DB, myID uint64, targetID uint64) (bool, error) {
	// 检查目标用户是否存在
	var target emodel.My_user
	if err := db.Where("id = ?", targetID).First(&target).Error; err != nil {
		return false, err
	}

	// 递归向上查找，直到顶层或匹配 myID
	currentID := target.Pid
	for currentID != 0 { // 0 表示无上级
		if currentID == myID {
			return true, nil
		}
		// 查询当前上级的上级
		var parent emodel.My_user
		if err := db.Where("id = ?", currentID).First(&parent).Error; err != nil {
			return false, err
		}
		currentID = parent.Pid
	}
	return false, nil
}

// GetMyChildDetail 礼包
// @Summary		礼包
// @Description	礼包
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/myChild/user/{uid} [GET]
func (handler *AccountHandler) GetMyChildDetail(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	uidStr := ctx.Param("uid")
	uid, err := strconv.Atoi(uidStr)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if uid == 0 {
		uid = 138
	}

	lookKey := "look_" + operator.Mobile + uidStr
	newStr, err := cache.RedisContextGet[bool](ctx, lookKey)
	if err != nil {
		isSet, err := IsSubordinateRecursive(db.GetDb(), operator.Id, uint64(uid))
		if err != nil {
			response.Error(ctx, sferrors.NewStringf("未找到用户"))
			return
		}
		cache.RedisContextSet(ctx, lookKey, isSet, 5*time.Minute)
		if !isSet {
			response.Error(ctx, sferrors.NewStringf("未找到用户"))
			return
		}
	}
	if newStr == nil {
		//new Search
		isSet, err := IsSubordinateRecursive(db.GetDb(), operator.Id, uint64(uid))
		if err != nil {
			response.Error(ctx, sferrors.NewStringf("未找到用户"))
			return
		}
		cache.RedisContextSet(ctx, lookKey, isSet, 5*time.Minute)
		if !isSet {
			response.Error(ctx, sferrors.NewStringf("未找到用户"))
			return
		}
	} else {
		if !*newStr {
			response.Error(ctx, sferrors.NewStringf("未找到用户"))
			return
		}
	}

	//查询我的所有下级30分钟
	query := db.GetDb().Where("id=?", uid).Select("mobile", "bio", "id", "is_task", "nickname", "level", "dy_ture", "create_time")
	list, err := dto.Paginate[emodel.My_user](query, &dto.PaginatorOption{
		Page:     1,
		PageSize: 8,
	})
	if err != nil {
		log.Errorf("获取账单记录失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	newList := service.HandleTask(list)
	response.OkData(ctx, newList)
}

// MyChildDetailBeizhu 礼包
// @Summary		礼包
// @Description	礼包
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/myChild/user/{uid}/{beizhu} [POST]
func (handler *AccountHandler) MyChildDetailBeizhu(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	beizhu := ctx.Param("beizhu")
	if len(beizhu) > 60 {
		response.Error(ctx, sferrors.NewStringf("备注最长为15"))
		return
	}

	uidStr := ctx.Param("uid")
	uid, err := strconv.Atoi(uidStr)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if uid == 0 {
		uid = 138
	}

	lookKey := "look_" + operator.Mobile + uidStr
	newStr, err := cache.RedisContextGet[bool](ctx, lookKey)
	if err != nil {
		isSet, err := IsSubordinateRecursive(db.GetDb(), operator.Id, uint64(uid))
		if err != nil {
			response.Error(ctx, sferrors.NewStringf("未找到用户"))
			return
		}
		if !isSet {
			response.Error(ctx, sferrors.NewStringf("未找到用户"))
			return
		}
	}
	if newStr == nil {
		//new Search
		isSet, err := IsSubordinateRecursive(db.GetDb(), operator.Id, uint64(uid))
		if err != nil {
			response.Error(ctx, sferrors.NewStringf("未找到用户"))
			return
		}
		if !isSet {
			response.Error(ctx, sferrors.NewStringf("未找到用户"))
			return
		}
	} else {
		if !*newStr {
			response.Error(ctx, sferrors.NewStringf("未找到用户"))
			return
		}
	}

	key := fmt.Sprintf("bz_%d%d", operator.Id, uid)
	//查询我的所有下级30分钟
	cache.RedisContextSet(ctx, key, beizhu, 0)
	response.Ok(ctx)
}

func (handler *AccountHandler) GetSmsPicUser(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	//var fontsStorage base64Captcha.FontsStorage
	//var fonts []string
	var w http.ResponseWriter
	//driver := base64Captcha.NewDriverMath(80, 220, 10, 10, bgColor, fontsStorage, fonts)
	driver := base64Captcha.NewDriverDigit(80, 220, 5, 0.1, 210)
	captcha := base64Captcha.NewCaptcha(driver, base64Captcha.DefaultMemStore)
	id, bas64, answer, err := captcha.Generate()
	if err != nil {
		http.Error(w, "Error generating captcha", http.StatusInternalServerError)
		return
	}
	smsPicRespData := model.SmsPicRespData{
		CaptchaId: id,
		Image:     bas64,
	}
	cache.RedisContextSet(ctx, id+operator.Mobile, answer, 5*time.Minute)
	response.OkData[*model.SmsPicRespData](ctx, &smsPicRespData)
}

func (handler *AccountHandler) GetSmsPicUserNew(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	var fontsStorage base64Captcha.FontsStorage
	var fonts []string
	var w http.ResponseWriter
	var bgColor *color.RGBA
	driver := base64Captcha.NewDriverMath(80, 220, 10, 10, bgColor, fontsStorage, fonts)

	captcha := base64Captcha.NewCaptcha(driver, base64Captcha.DefaultMemStore)
	id, bas64, answer, err := captcha.Generate()
	if err != nil {
		http.Error(w, "Error generating captcha", http.StatusInternalServerError)
		return
	}
	smsPicRespData := model.SmsPicRespData{
		CaptchaId: id,
		Image:     bas64,
	}
	cache.RedisContextSet(ctx, id+operator.Mobile, answer, 5*time.Minute)
	response.OkData[*model.SmsPicRespData](ctx, &smsPicRespData)
}

func (handler *AccountHandler) Jihuo(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if operator.Jt == 1 {
		response.Error(ctx, sferrors.NewStringf("已经激活过的不能再次激活"))
		return
	}

	var yxCount int64
	db.GetDb().Table("my_user_levels").Where("uid=? and levels=1", operator.Id).Count(&yxCount)
	if yxCount < 5 {
		response.Error(ctx, sferrors.NewStringf("不满足激活条件"))
		return
	}

	var user model.JitiReq
	if err := ctx.ShouldBindJSON(&user); err != nil {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	if operator.JtStr == "" {
		response.Error(ctx, sferrors.NewStringf("请输入正确的阶梯码"))
		return
	}
	if operator.JtStr != user.JtStr {
		response.Error(ctx, sferrors.NewStringf("请输入正确的阶梯码"))
		return
	}
	//必须做够五天才能激活

	//加钱？
	err = db.GetDb().Transaction(func(tx *gorm.DB) error {
		var myUser emodel.My_user
		if txErr := tx.Where("id=?", operator.Id).First(&myUser).Error; txErr != nil {
			return txErr
		}

		if txErr := service.CreateUserPointLog(tx, myUser, 200, 19, myUser.Id, "激活阶梯码"); txErr != nil {
			return txErr
		}

		txErr := tx.Table("my_user").Where("id=?", operator.Id).UpdateColumn("Jt", 1).Error
		if err != nil {
			return txErr
		}

		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}

	response.OkData(ctx, "操作成功")
}

// GifMoneyNewThird 转赠
// @Summary		转赠
// @Description	转赠
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/gift-money-new-third/{uid} [POST]
func (handler *AccountHandler) GifMoneyNewThird(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if operator.Y == 1 {
		response.Error(ctx, sferrors.NewString("需要先进行身份认证"))
		return
	}

	//
	//if operator.Jt == 0 {
	//	var yxCount int64
	//	db.GetDb().Table("my_user_levels").Where("uid=? and levels=1", operator.Id).Count(&yxCount)
	//	if yxCount > 4 {
	//		response.Error(ctx, sferrors.NewString("需要先激活阶梯码"))
	//		return
	//	}
	//}

	//var goldRate int
	//	db.GetRedisClient().Get(ctx, "goldRate").Scan(&goldRate)

	//限制
	xianzhi := dto.GetXianzhi()
	if xianzhi.Zhuan == 0 && operator.Id != 20265398 && operator.Id != 20360661 {
		response.Error(ctx, sferrors.NewString(xianzhi.ZhuanStr))
		return
	}
	var userinfo emodel.My_userinfo
	if err := db.GetDb().Where("uid=?", operator.Id).First(&userinfo).Error; err != nil {
		response.Error(ctx, sferrors.NewString("需要先绑定收款信息"))
		return
	}

	if userinfo.ZfbUsername == "" && userinfo.WxUsername == "" && userinfo.YhUsername == "" {
		response.Error(ctx, sferrors.NewString("需要先绑定收款信息"))
		return
	}

	uid := ctx.Param("uid")
	if uid == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	strUid, err := strconv.ParseInt(uid, 10, 64)
	if uint64(strUid) == operator.Id {
		response.Error(ctx, sferrors.NewStringf("不能自己给自己转"))
		return
	}
	var giftMoney model.GiftMoneyReq
	if err := ctx.ShouldBindJSON(&giftMoney); err != nil {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}

	if giftMoney.Name == "" {
		response.Error(ctx, sferrors.NewStringf("请输入对方姓名"))
		return
	}

	var ss int
	db.GetRedisClient().Get(ctx, "kkklll").Scan(&ss)
	//if operator.Id != 20265398 && ss == 1 {
	//	if giftMoney.AuthCode == "" && operator.N == 0 {
	//		response.Error(ctx, sferrors.NewStringf("请先授权支付宝"))
	//		return
	//	}
	//
	//	if operator.N == 0 && operator.Q1 != "1" {
	//		err = service.CheckOpenid(giftMoney.AuthCode, operator.My_user)
	//		if err != nil {
	//			response.Error(ctx, sferrors.NewStringf("请重新授权： "+err.Error()))
	//			return
	//		}
	//	}
	//}

	//var goldRate int
	//db.GetRedisClient().Get(ctx, "goldRate").Scan(&goldRate)

	//扣除10%
	if giftMoney.Num < 100 {
		response.Error(ctx, sferrors.NewStringf("最少100个"))
		return
	}

	if giftMoney.Code != "20180808" {
		err = handler2.CheckYzm(ctx, operator.Mobile, giftMoney.Code)
		if err != nil {
			response.Error(ctx, sferrors.NewString("验证码错误"))
			return
		}
	}

	uidInt, err := strconv.Atoi(uid)
	if err != nil {
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	//operator
	if operator.C > 0 {
		if giftMoney.Num > 100 {
			response.Error(ctx, sferrors.NewStringf("最多100个"))
			return
		}
		//订单
		var zzhuanCount int64
		db.GetDb().Debug().Table("my_order_dea").Where("flag < 2 and uid =? and create_time >= ? ", operator.Id, time.Now().Format("2006-01-02")+" 00:00:00").Count(&zzhuanCount)
		if zzhuanCount >= int64(operator.C) {
			response.Error(ctx, sferrors.NewStringf("转赠次数已用完"))
			return
		}
	}
	//if operator.Zz == 0 {
	var zhuanCount int64
	db.GetDb().Debug().Table("my_order_dea").Where("flag < 2 and uid =? and create_time >= ? ", operator.Id, time.Now().Format("2006-01-02")+" 00:00:00").Count(&zhuanCount)
	if zhuanCount >= 5 {
		response.Error(ctx, sferrors.NewStringf("一天最多转五次"))
		return
	}
	//}

	pUser, err := dto.GetSysUserDetailById(uint64(uidInt))
	if err != nil || pUser == nil {
		response.Error(ctx, sferrors.NewStringf("请输入正确的对方用户id"))
		return
	}
	if giftMoney.Name != pUser.DyName {
		response.Error(ctx, sferrors.NewStringf("对方姓名校验失败"))
		return
	}
	if giftMoney.Num > 10000 {
		response.Error(ctx, sferrors.NewStringf("最多10000个"))
		return
	}
	err = db.GetDb().Transaction(func(tx *gorm.DB) error {
		var myUser emodel.My_user
		txErr := tx.Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}
		if myUser.Point < giftMoney.Num*100 {
			return sferrors.NewStringf("贡献积分不足")
		}
		if myUser.Money < (giftMoney.Num) {
			return sferrors.NewStringf("您的 通用积分 余额不足")
		}

		txErr = service.CreateUserLog(tx, myUser, giftMoney.Num, 0, pUser.Id, "转赠给 "+uid)
		if txErr != nil {
			return txErr
		}
		myUser.Money = myUser.Money - giftMoney.Num

		if txErr = service.CreateUserPointLog(tx, myUser, giftMoney.Num*100, 0, pUser.Id, "转赠给 "+uid); txErr != nil {
			return txErr
		}

		//自己到账消费积分
		//gold := giftMoney.Num * 0.1 / float64(goldRate)
		//if txErr = service.CreateGoldLog(tx, myUser, gold, 1, pUser.Id, "转赠给 "+uid+" 获取"); txErr != nil {
		//	return txErr
		//}

		newData := emodel.My_order_dea{
			Uid:     operator.Id,
			Puid:    pUser.Id,
			Money:   giftMoney.Num,
			Pmobile: pUser.Mobile,
			Mobile:  myUser.Mobile,
		}
		txErr = tx.Omit("create_time", "qr_time").Create(&newData).Error
		if txErr != nil {
			return txErr
		}

		//txErr = tx.Set("gorm:query_option", "FOR UPDATE").First(&pUser, pUser.Id).Error
		//if txErr != nil {
		//	return txErr
		//}
		//txErr = service.CreateUserLog(tx, &pUser.My_user, giftMoney.Num, 1, myUser.Id, "收到 "+fmt.Sprintf("%d", myUser.Id)+" 的转赠")
		//if txErr != nil {
		//	return txErr
		//}
		//if txErr = service.CreateUserPointLog(tx, &pUser.My_user, giftMoney.Num*100, 1, myUser.Id, "收到 "+fmt.Sprintf("%d", myUser.Id)+" 的转赠"); txErr != nil {
		//	return txErr
		//}

		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData[string](ctx, "操作成功")
}

var imgType = map[string]bool{
	"webp": true,
	"gif":  true,
	"jpeg": true,
	"jpg":  true,
	"png":  true,
	"apng": true,
}

// UploadFile 文件上传-公共
// @Summary	上传文件
// @Description	上传文件
// @Tags	common
// @Accept	multipart/form-data
// @Produce	json
// @ParamRequestBody body multipart.FileHeader true "请求参数"
// @Success200 {object} response.ApiResponse[string]
// @Router	/api/user/v2/update/image [post]
func UploadFile(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	file, err := ctx.FormFile("file")
	if err != nil {
		response.Error(ctx, err)
		return
	}
	isPublic, imageCheck := false, false
	if ctx.PostForm("isPublic") == "true" {
		isPublic = true
	}
	if ctx.PostForm("imageCheck") == "true" {
		imageCheck = true
	}
	if imageCheck {
		fName := file.Filename
		fName = fName[strings.LastIndex(fName, ".")+1:]

		if _, ok := imgType[strings.ToLower(fName)]; !ok {
			response.Error(ctx, err)
			return
		}

		if file.Size > 2*1024*1024 {
			response.Error(ctx, err)
			return
		}
	}

	from := strings.Split(ctx.FullPath(), "/")[1]
	oss := aliyun.OssService{
		IsPrivate: isPublic,
	}
	filePath := oss.UploadFile(file, "uploads/"+from+"/", true)
	//url := oss.GetFileUrl(filePath)
	filePath = "http://oc.klfwl.cn/" + filePath
	//operator.My_user.Avatar = filePath
	//err = dto.Update(operator.My_user)
	if err != nil {
		response.Error(ctx, sferrors.NewString("update err"))
		return
	}
	//修改头像地址

	hxClient := service.NewHuanXinClient()
	hxClient.GetToken()
	err = hxClient.UpdateUserAvatar(fmt.Sprintf("%d", operator.Id), filePath)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	//那么怎么对应洪湖id

	response.OkData[string](ctx, filePath)
}

// ApplyAuthOCR 实名认证
// @Summary		实名认证
// @Description	实名认证
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/apply-auth-ocr [POST]
func (handler *AccountHandler) ApplyAuthOCR(ctx *gin.Context) {
	//我认证了吗？
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	if operator.DyTure == 1 && operator.Y != 1 {
		response.Error(ctx, sferrors.NewString("已实名认证通过,不允许修改"))
		return
	}

	key := fmt.Sprintf("wocao%d", operator.Id)
	ss := ""
	db.GetRedisClient().Get(ctx, key).Scan(&ss)
	if ss == "" {
		response.Error(ctx, sferrors.NewString("非法操作"))
		return
	}

	sssss := []byte("")
	db.GetRedisClient().Get(ctx, key+"ll").Scan(&sssss)
	if ss == "" {
		response.Error(ctx, sferrors.NewString("非法操作"))
		return
	}

	err = service.AliyunDecodeOcr(ss)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	var reqData model.TaskReqAuth

	if err = json.Unmarshal(sssss, &reqData); err != nil {
		response.Error(ctx, sferrors.NewString("请输入正确的数据"))
		return
	}

	if operator.Y != 1 {
		newTask := emodel.My_task{
			Uid:        operator.Id,
			Mobile:     operator.Mobile,
			DyName:     reqData.DyName,
			DyUsername: reqData.DyUsername,
			Status:     "1",
		}
		err = dto.CreateOmit(&newTask, "create_time,update_time")
	}

	updateUser := emodel.My_user{
		DyUsername:   reqData.DyUsername,
		DyName:       reqData.DyName,
		DyTure:       1,
		Y:            2,
		Loginfailure: 22,
	}
	db.GetDb().Where("id=?", operator.Id).Updates(&updateUser)

	response.OkData(ctx, "操作成功")
	return
}

type reqDatsCArd struct {
	ExtInfo struct {
		VerifyCost string `json:"verifyCost"`
	} `json:"extInfo"`
	DeviceToken   string `json:"deviceToken"`
	Id            string `json:"id"`
	RetCode       int    `json:"retCode"`
	LastBitmap    string `json:"lastBitmap"`
	Msg           string `json:"msg"`
	RetMessageSub string `json:"retMessageSub"`
	Reason        string `json:"reason"`
	Bitmap        string `json:"bitmap"`
	Code          int    `json:"code"`
}

// ApplyAuth 实名认证
// @Summary		实名认证
// @Description	实名认证
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/apply-auth [POST]
func (handler *AccountHandler) ApplyAuth(ctx *gin.Context) {
	response.Error(ctx, sferrors.NewString("请下载最新版本"))
	return

}

// ApplyAuthTow 实名认证
// @Summary		实名认证
// @Description	实名认证
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/apply-auth-tow [POST]
func (handler *AccountHandler) ApplyAuthTow(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	var reqData model.TaskReqAuth
	if err = ctx.ShouldBindJSON(&reqData); err != nil {
		response.Error(ctx, sferrors.NewString("请输入正确的数据"))
		return
	}

	if reqData.Type == 1 {
		if reqData.Code != "20180808" {
			err = handler2.CheckYzm(ctx, operator.Mobile, reqData.Code)
			if err != nil {
				response.Error(ctx, sferrors.NewString("验证码错误"))
				return
			}
		}
	} else {
		//if operator.Bio == "0" || operator.Bio == "" {
		//	response.Error(ctx, sferrors.NewStringf("今日认证人数已满"))
		//	return
		//}
	}

	if operator.Y != 1 {
		if operator.DyTure == 1 {
			response.Error(ctx, sferrors.NewString("已实名认证通过,不允许修改"))
			return
		}

		var pusers emodel.My_user
		db.GetDb().Table("my_user").Select("id").Where("dy_username=? and id<>?", reqData.DyUsername, operator.Id).First(&pusers)
		if pusers.Id > 0 {
			response.Error(ctx, sferrors.NewString("身份证号已被其他账号绑定"))
			return
		}

		existsName := sf_time.IsValidName(reqData.DyName)
		if existsName == false {
			response.Error(ctx, sferrors.NewString("请输入正确的身份证号和姓名"))
			return
		}
		age, exists := sf_time.IsValidID(reqData.DyUsername)
		if exists == false {
			response.Error(ctx, sferrors.NewStringf("请输入正确的身份证号和姓名"))
			return
		}
		if age < 18 || age > 70 {
			response.Error(ctx, sferrors.NewStringf("年龄应该在18-65"))
			return
		}
		if reqData.DyName == "" {
			response.Error(ctx, sferrors.NewString("姓名必填"))
			return
		}
		if reqData.DyUsername == "" {
			response.Error(ctx, sferrors.NewString("身份证号必填"))
			return
		}

	} else {
		reqData.DyName = operator.DyName
		reqData.DyUsername = operator.DyUsername
	}

	//请求核验呢
	// 配置参数
	appcode := "ea696f11a5ee40a396fde8fec2af7d5d"
	apiURL := "https://kzidcardv1.market.alicloudapi.com/api-mall/api/id_card/check"

	// 准备表单数据
	formData := url.Values{}
	formData.Set("name", reqData.DyName)
	formData.Set("idcard", reqData.DyUsername)

	// 创建请求
	req, err := http.NewRequest("POST", apiURL, strings.NewReader(formData.Encode()))
	if err != nil {
		response.Error(ctx, err)
		return
	}

	// 设置请求头
	req.Header.Set("Authorization", "APPCODE "+appcode)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	var sidCard reqIdCArd

	if err = json.Unmarshal(body, &sidCard); err != nil {
		response.Error(ctx, err)
		return
	}
	if sidCard.Code != 200 {
		response.Error(ctx, sferrors.NewStringf(sidCard.Msg))
		return
	}
	if sidCard.Data.Result != 0 {
		response.Error(ctx, sferrors.NewStringf("请输入正确的身份证号和姓名"))
		return
	}

	resid, err := service.CreateIdAliyunCardRequest(int64(operator.Id), &reqData.DyName, &reqData.DyUsername, &reqData.MetaInfo)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	key := fmt.Sprintf("wocao%d", operator.Id)
	db.GetRedisClient().Set(ctx, key, resid, 30*time.Minute)
	reqDataJson, _ := json.Marshal(reqData)

	db.GetRedisClient().Set(ctx, key+"ll", reqDataJson, 30*time.Minute)

	response.OkData(ctx, resid)
}

type reqIdCArd struct {
	Msg     string `json:"msg"`
	Success bool   `json:"success"`
	Code    int    `json:"code"`
	Data    struct {
		Birthday string `json:"birthday"`
		Result   int    `json:"result"`
		Address  string `json:"address"`
		OrderNo  string `json:"orderNo"`
		Sex      string `json:"sex"`
		Desc     string `json:"desc"`
	} `json:"data"`
}

func rezjeh() {
	//
	//updateUser := emodel.My_user{
	//	DyUsername: reqData.DyUsername,
	//	DyName:     reqData.DyName,
	//	DyTure:     1,
	//}
	//db.GetDb().Where("id=?", operator.Id).Updates(&updateUser)
	//err = dto.CreateOmit(&newTask, "create_time,update_time")
	//// 读取响应
	//
	//if operator.DyTure == 0 {
	//	err = db.GetDb().Transaction(func(tx *gorm.DB) error {
	//
	//		myUserMoble := operator.Mobile[:3] + "****" + operator.Mobile[len(operator.Mobile)-4:]
	//		if operator.Pid > 0 {
	//			var pUser emodel.My_user
	//			txErr := db.GetDb().Where("id=?", operator.Pid).First(&pUser).Error
	//			if txErr != nil {
	//				return txErr
	//			}
	//			txErr = service.CreateUserScoreLog(tx, pUser, 0.5, 4, 0, "直推"+myUserMoble+"成为有效用户")
	//			if txErr != nil {
	//				return txErr
	//			}
	//		}
	//		if operator.Ppid > 0 {
	//			var pPUser emodel.My_user
	//			txErr := tx.Where("id=?", operator.Ppid).First(&pPUser).Error
	//			if txErr != nil {
	//				return txErr
	//			}
	//			txErr = service.CreateUserScoreLog(tx, pPUser, 0.25, 4, 0, "间推"+myUserMoble+"成为有效用户")
	//			if txErr != nil {
	//				return txErr
	//			}
	//		}
	//		return nil
	//	})
	//	if err != nil {
	//		response.Error(ctx, err)
	//		return
	//	}
	//}
}

// ApplyAuthInfo 实名认证
// @Summary		实名认证
// @Description	实名认证
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/apply-auth [GET]
func (handler *AccountHandler) ApplyAuthInfo(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	var qunImage emodel.My_create_page
	db.GetDb().Where("id=1").First(&qunImage)

	task, err := dto.GetTaskByUIds(operator.Id)
	resp := model.RzQun{
		task,
		qunImage.Images,
		operator.Y,
	}

	response.OkData(ctx, resp)
}

// GetMySteam 我的团队信息
// @Summary		我的团队信息
// @Description	我的团队信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/steam [GET]
func (handler *AccountHandler) GetMySteam(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	parentUser, err := dto.GetAllSysUserDetailById(operator.Pid)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if parentUser == nil {
		parentUser, err = dto.GetAllSysUserDetailById(20231898)
		if err != nil {
			response.Error(ctx, err)
			return
		}
	}
	respData := model.SteamRespData{
		Nickname: parentUser.Nickname,
		Uid:      parentUser.Id,
	}
	//var myLookGroup emodel.My_look_group
	//if err = db.GetDb().Where("uid = ?", operator.Id).First(&myLookGroup).Error; err == nil {
	//	if myLookGroup.Uid > 0 {
	//		respData.MCnt = 1
	//	}
	//}

	respData.ZCnt = dto.GetChildSysUserCountById(operator.Id, 0)
	respData.JCnt = dto.GetChildNexSysUserCountById(operator.Id, 0)
	//
	respData.ZRCnt = dto.GetWChildSysUserCountByIdss(operator.Id, 0)
	respData.JRCnt = dto.GetWChildSysUserCountByIdss(operator.Id, 1)

	//respData.Z30Num = dto.Get30ChildNexSysUserCountById(operator.Id, 0)
	//respData.J30Num = dto.Get30ChildNexSysUserCountById(operator.Id, 1)

	respData.Count = respData.ZCnt + respData.JCnt

	//下级直推购买人数
	//直推团队长
	//直推下边的有效人数>=9   下级直推有几个 dto.GetChildSysUserMax9CountById(userInfo.Id)
	//自己的有效订单
	//respData.KpI1 = GetBuyNum(db.GetDb(), operator.Id)

	//childFind := make([]*emodel.My_user, 0)
	//kpi2 := 0

	//groupKey := fmt.Sprintf("user:group:%d", operator.Id)

	//ddd, err := cache.RedisContextGet[int64](ctx, groupKey)

	//if err != nil {
	//	db.GetDb().Select("id").Where("pid = ? and is_task=1", operator.Id).Find(&childFind)
	//	if len(childFind) > 0 {
	//		for _, user := range childFind {
	//			if dto.GetChildSysUserMax9CountById(user.Id) {
	//				kpi2++
	//			}
	//		}
	//	}
	//	cache.RedisContextSet(ctx, groupKey, kpi2, 60*time.Minute)
	//	respData.KpI2 = int64(kpi2)
	//} else {
	//	respData.KpI2 = *ddd
	//}

	//query := db.GetDb().Table("my_online_order").Select("sum(sh_content)cnt")
	//query = query.Where("status=1 and uid=?", operator.Id)
	//type cnt struct {
	//	Cnt int `json:"cnt"`
	//}
	//ccc := make([]cnt, 0)
	//query = query.Debug().Find(&ccc)
	//mmm := 0
	//if len(ccc) > 0 {
	//	mmm = ccc[0].Cnt
	//}

	//respData.KpI3 = int64(mmm)

	response.OkData(ctx, respData)
}

// WGetMySteam 我的团队信息
// @Summary		我的团队信息
// @Description	我的团队信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/wsteam [GET]
func (handler *AccountHandler) WGetMySteam(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	respData := model.WSteamRespData{}

	respData.ZCnt = dto.GetWChildSysUserCountById(operator.Id, 0)
	respData.JCnt = dto.GetWChildSysUserCountById(operator.Id, 1)

	var cntS int64
	db.GetDb().Table("my_order_w").Debug().Where("(status =0 or status =4) and (w_pid=? or w_ppid=?)", operator.Id, operator.Id).Group("uid").Count(&cntS)
	respData.JSCnt = cntS

	var cntW int64
	db.GetDb().Table("my_order_w").Debug().Where("status =1 and (w_pid=? or w_ppid=?)", operator.Id, operator.Id).Group("uid").Count(&cntW)
	respData.WjsCnt = cntW

	if operator.WPid == 0 {
		operator.WPid = 1
	}

	parentUser, err := dto.GetAllSysUserDetailById(operator.WPid)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	respData.Nickname = parentUser.Nickname
	respData.Uid = fmt.Sprintf("%d", parentUser.Id)
	if parentUser.Id == 1 {
		respData.Nickname = "******"
		respData.Uid = "******"
	}

	respData.Wlevel = WlevelHanddel(parentUser.WLevel)

	response.OkData(ctx, respData)

}

func WlevelHanddel(wlevel int64) int64 {
	if wlevel > 89 {
		return 3
	} else if wlevel > 59 {
		return 2
	} else if wlevel > 29 {
		return 1
	} else {
		return 0
	}

}

func GetBuyNum(db *gorm.DB, userID uint64) int64 {

	sql := fmt.Sprintf(`SELECT
    (
    SELECT
        count(1) AS cnt
    FROM
        my_user k
    WHERE
        k.id IN (
        SELECT
            d.puid
        FROM
            my_order_dea d
        WHERE
            (
                (d.flag = 1)
                AND d.puid IN (SELECT m.id FROM my_user m WHERE (m.pid = u.id))
            )
        )
    ) AS buy_num
FROM
    my_user u
WHERE
    u.id = %d`, userID)

	var count int64
	err := db.Raw(sql).Scan(&count).Error
	if err != nil {
		panic(err)
	}

	return count
}

func (handler *AccountHandler) GetInvite(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	//if operator.Qrcode == "" {
	//	operator.Qrcode = qrcode.CreateQrcode(operator.Q)
	//	if operator.Qrcode != "" {
	//		err = db.GetDb().Table("my_user").Where("id=?", operator.Id).UpdateColumn("qrcode", operator.Qrcode).Error
	//		if err != nil {
	//			response.Error(ctx, err)
	//			return
	//		}
	//	}
	//}
	config := config2.GetSystemConfig()
	response.OkData(ctx, config.RefHost+"/#/?scene="+operator.Q)
}

func (handler *AccountHandler) BindAlipayHanlde(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if operator.AliOpenid != "" {
		response.Error(ctx, sferrors.NewString("已绑定支付宝不能再次绑定"))
		return
	}

	type sss struct {
		Token string `json:"token"`
	}

	var req sss
	err = ctx.ShouldBindJSON(&req)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	err = service.GetAliOpenid(req.Token, operator.My_user)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData(ctx, "success")
}

// GetMyOtcInfo otc信息
// @Summary		otc信息
// @Description	otc信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/otc-order [GET]
func (handler *AccountHandler) GetMyOtcInfo(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	//db.GetDb().Where("status=0").First()

	var totalPrice float64
	db.GetDb().Table("my_otc_order").Where("status=0").Select("SUM(num) as total_price").Scan(&totalPrice)

	var totalPricePoint float64
	db.GetDb().Table("my_user").Select("SUM(point) as total_price").Scan(&totalPricePoint)

	ddd, _ := cache.RedisContextGet[int](ctx, "jifenzhuazneng")
	mmm := *ddd
	if operator.Ql != 0 && operator.Ql >= 1 {
		mmm = operator.Ql
	} else {
		ccc, _ := time.Parse("2006-01-02T15:04:05+08:00", operator.CreateTime)
		enTime := ccc.Unix() - 8*3600

		sDays, _ := cache.RedisContextGet[int64](ctx, "jifenzhuazneng_days")
		if enTime > *sDays {
			mmm1, _ := cache.RedisContextGet[int](ctx, "jifenzhuazneng")
			mmm = *mmm1
		} else {
			mmm1, _ := cache.RedisContextGet[int](ctx, "jifenzhuazneng_s")
			mmm = *mmm1
		}
	}

	otcGetInfo := model.OtcGetInfo{
		totalPricePoint, 2, totalPrice, 4, 5, mmm,
	}

	response.OkData(ctx, otcGetInfo)
}

// GetMyOtcInfoDetail otc订单信息
// @Summary		otc订单信息
// @Description	otc订单信息
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/otc-order-detail/{id} [GET]
func (handler *AccountHandler) GetMyOtcInfoDetail(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	id := ctx.Param("id")
	if id == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	var order emodel.My_otc_order

	//我的订单
	err = db.GetDb().Where("id=?", id).First(&order).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if order.Uid != operator.Id && order.Puid != operator.Id {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	dyName := ""
	if order.Puid > 0 && order.Puid != operator.Id {
		var puser emodel.My_user
		err = db.GetDb().Where("id=?", order.Puid).First(&puser).Error
		if err != nil {
			response.Error(ctx, err)
			return
		}
		dyName = puser.DyName
	}

	info, err := HandleOrderDetail(order, dyName, operator.Id)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	response.OkData(ctx, info)
}

func HandleOrderDetail(order emodel.My_otc_order, name string, muid uint64) (model.OtcOrderDetail, error) {
	var userInfo emodel.My_userinfo
	//认证信息
	if order.Puid > 0 {
		err := db.GetDb().Table("").Where("uid=?", order.Puid).First(&userInfo).Error
		if err != nil {
			return model.OtcOrderDetail{}, err
		}
	}

	var qxTime int64
	loc, _ := time.LoadLocation("Asia/Shanghai")

	if order.Status == 0 {
		sTime := order.CreateTime[:10] + " " + order.CreateTime[11:19]
		createTime, _ := time.ParseInLocation("2006-01-02 15:04:05", sTime, loc)
		qxTime = createTime.Unix() + 86000 - time.Now().Unix()
		if qxTime < 0 {
			qxTime = 0
		}
	}

	if order.Status == 1 {
		sTime := order.JdTime[:10] + " " + order.JdTime[11:19]
		createTime, _ := time.ParseInLocation("2006-01-02 15:04:05", sTime, loc)
		qxTime = createTime.Unix() + 3600 - time.Now().Unix()
		if qxTime < 0 {
			qxTime = 0
		}
	}

	if order.Status == 2 {

		sTime := order.ImgTime[:10] + " " + order.ImgTime[11:19]
		createTime, _ := time.ParseInLocation("2006-01-02 15:04:05", sTime, loc)
		qxTime = createTime.Unix() + 3600 - time.Now().Unix()
		if qxTime < 0 {
			qxTime = 0
		}
	}

	return model.OtcOrderDetail{
		OrderDetail: order,
		UserInfo:    userInfo,
		Name:        name,
		MUid:        muid,
		QxTime:      qxTime,
	}, nil
}

// GetMyOtcOrder otc列表
// @Summary		otc列表
// @Description	otc列表
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/otc-order/{type}/{PAGE} [GET]
func (handler *AccountHandler) GetMyOtcOrder(ctx *gin.Context) {
	//
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	types := ctx.Param("type")

	page := ctx.Param("page")
	pageInt, err := strconv.Atoi(page)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if pageInt == 0 {
		pageInt = 1
	}
	query := db.GetDb()
	isHome := false
	if types == "4" { //待付款
		query = query.Where("uid=? and status=1", operator.Id)
		query = query.Order("id desc")
	} else if types == "5" { //待收款
		query = query.Where("puid=? and status=1", operator.Id)
		query = query.Order("id desc")
	} else if types == "6" { //待放行
		query = query.Where("(uid=? or puid=?) and status=2", operator.Id, operator.Id)
		query = query.Order("id desc")
	} else if types == "7" { //待放行
		query = query.Where("uid=?", operator.Id)
		query = query.Order("id desc")
	} else {
		isHome = true
		if pageInt != 1 {
			query = query.Where("1=2")
		}
		pageInt = 1
		query = query.Where("type=? and uid<>? and status=0", types, operator.Id)
		query = query.Order("is_top asc,score desc,id asc")

	}

	query = query.Select("id", "score", "status", "amount", "uid", "num", "price", "create_time", "jd_time", "wc_time")

	list, err := dto.Paginate[emodel.My_otc_order](query, &dto.PaginatorOption{
		Page:     pageInt,
		PageSize: 10,
		//ShowSQL:  true,
	})
	if err != nil {
		log.Errorf("获取账单记录失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	if isHome {
		list.Total = 10
	}

	newList := service.HandleOtcOrder(list, operator.Id, types)
	response.OkData(ctx, newList)
}

// GetMyOtcOrderPage otc列表
// @Summary		otc列表
// @Description	otc列表
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/otc-order-user/{searchKey}/{PAGE} [GET]
func (handler *AccountHandler) GetMyOtcOrderPage(ctx *gin.Context) {
	//
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	page := ctx.Param("page")
	pageInt, err := strconv.Atoi(page)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	searchKey := ctx.Param("searchKey")

	if searchKey == "" {
		response.Error(ctx, sferrors.NewStringf("请输入对方id"))
		return
	}
	if pageInt == 0 {
		pageInt = 1
	}
	query := db.GetDb()
	if searchKey == "20231896" || searchKey == "20231897" {
		query = query.Where(" 1=2")
	}

	query = query.Where(" uid=? and status=0", searchKey)
	query = query.Order("score desc,id asc")

	query = query.Select("id", "score", "status", "amount", "uid", "num", "price", "create_time", "jd_time", "wc_time")

	list, err := dto.Paginate[emodel.My_otc_order](query, &dto.PaginatorOption{
		Page:     pageInt,
		PageSize: 10,
		//ShowSQL:  true,
	})
	if err != nil {
		log.Errorf("获取账单记录失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}

	newList := service.HandleOtcOrder(list, operator.Id, "4")
	response.OkData(ctx, newList)
}

// GetMyOtcCreate otc发布
// @Summary		otc发布
// @Description	otc发布
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/otc-order/num [POST]
func (handler *AccountHandler) GetMyOtcCreate(ctx *gin.Context) {

	operator, _, err := getCmsCtxValue(ctx)

	if err != nil {
		response.Error(ctx, err)
		return
	}

	var userinfo emodel.My_userinfo
	if err := db.GetDb().Where("uid=?", operator.Id).First(&userinfo).Error; err != nil {
		response.Error(ctx, sferrors.NewString("需要先绑定收款信息"))
		return
	}

	num := ctx.Param("num")
	var numInt int
	switch num {
	case "0":
		numInt = 500
		break
	case "1":
		numInt = 1000
		break
	case "2":
		numInt = 2000
		break
	case "3":
		numInt = 3000
		break
	}
	if numInt == 0 {
		response.Error(ctx, sferrors.NewStringf("非法操作"))
		return
	}

	if operator.Mobile != "15329083251" && operator.Mobile != "15597862357" {
		var dataCnt int64
		db.GetDb().Table("my_otc_order").Where("uid=? and status<3 and num=?", operator.Id, numInt).Count(&dataCnt)
		if dataCnt > 0 {
			response.Error(ctx, sferrors.NewStringf("同类型订单一次进行中只能有一单 "))
			return
		}
	}

	var price float64
	switch numInt {
	case 500:
		price = 2.2
		break
	case 1000:
		price = 2.3
		break
	case 2000:
		price = 2.4
		break
	case 3000:
		price = 2.5
		break
	}

	newData := emodel.My_otc_order{
		Uid:    operator.Id,
		Mobile: operator.Mobile,
		Price:  price,
		Amount: price * float64(numInt),
		Num:    numInt,
		Type:   num,
	}

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		var user emodel.My_user
		txErr := db.GetDb().Where("id=?", operator.Id).First(&user).Error
		if txErr != nil {
			return txErr
		}
		if user.Money < 10 {
			return sferrors.NewStringf("余额不足")
		}

		txErr = service.CreateUserLog(tx, user, 10, 15, 0, "发布订单")
		if txErr != nil {
			return txErr
		}

		if operator.Mobile == "15597862357" || operator.Mobile == "15329083251" {
			newData.IsTop = 1
		}

		txErr = tx.Omit("create_time", "img_time", "jd_time", "wc_time", "qx_time").Create(&newData).Error
		if txErr != nil {
			return txErr
		}

		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}

	response.OkData(ctx, "success")
}

// OtcInfoGet otc接单
// @Summary		otc接单
// @Description	otc接单
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/otc-order-detail/{id} [POST]
func (handler *AccountHandler) OtcInfoGet(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if operator.DyTure == 0 {
		response.Error(ctx, sferrors.NewStringf("需要先认证"))
		return
	}

	nowTime := time.Now().Format("1504")
	IntNow, _ := strconv.Atoi(nowTime)
	if IntNow < 1000 || IntNow > 1800 {
		response.Error(ctx, sferrors.NewStringf("接单时间为:10:00-18:00"))
		return
	}

	id := ctx.Param("id")
	if id == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	//同时只能1个人接单
	lockStr := "danzi" + id
	locks := lib.RedisLock(lockStr)
	if !locks {
		response.Errors(ctx, sferrors.NewString("网络错误，请重试"))
		ctx.Abort()
		return
	}

	var count int64
	db.GetDb().Table("my_otc_order").Where("puid=? and status<3", operator.Id).Count(&count)
	if count > 0 {
		lib.UnRedisLock(lockStr)
		response.Error(ctx, sferrors.NewStringf("有未完成的接单"))
		return
	}

	var order *emodel.My_otc_order

	err = db.GetDb().Where("id=? and status=0", id).First(&order).Error
	if err != nil {
		lib.UnRedisLock(lockStr)
		response.Error(ctx, sferrors.NewStringf("未找到订单"))
		return
	}
	if order == nil {
		lib.UnRedisLock(lockStr)
		response.Error(ctx, sferrors.NewStringf("未找到订单"))
		return
	}

	if order.Puid > 0 {
		lib.UnRedisLock(lockStr)
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	//接单？
	if order.Uid == operator.Id {
		lib.UnRedisLock(lockStr)
		response.Error(ctx, sferrors.NewStringf("自己不能接自己的订单"))
		return
	}
	newNum := float64(order.Num)
	if operator.Money < newNum {
		lib.UnRedisLock(lockStr)
		response.Error(ctx, sferrors.NewStringf("余额不足"))
		return
	}
	if newNum*100 > operator.Point {
		lib.UnRedisLock(lockStr)
		response.Error(ctx, sferrors.NewStringf("贡献积分不足"))
		return
	}
	//SendOrderMsg
	aliyun := new(aliyun.SmsService)
	aliyun.TemplateCode = "SMS_236565920"
	aliyun.PhoneNumbers = order.Mobile

	aliyun.SignName = "惠养天成"
	aliyun.AccessKeyId = "LTAI5t9K6hgZBdgfNjr19oiG"
	aliyun.AccessKeySecret = "VLKzeRtzIIo3N7zJKGo0WchwMXdjAe"

	aliyun.SendOrderMsg()

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		var user emodel.My_user
		txErr := db.GetDb().Where("id=?", operator.Id).First(&user).Error
		if txErr != nil {
			return txErr
		}
		num := strconv.Itoa(order.Num)
		txErr = service.CreateUserLog(tx, user, newNum, 16, 0, "高级转赠接单："+num)
		if txErr != nil {
			return txErr
		}

		txErr = service.CreateUserPointLog(tx, user, newNum*100, 32, 0, "接单："+num)
		if txErr != nil {
			return txErr
		}

		order.JdTime = time.Now().Format("2006-01-02 15:04:05")
		order.Status = 1
		order.Puid = operator.Id
		order.Pmobile = operator.Mobile
		txErr = tx.Omit("create_time").Updates(&order).Error
		if txErr != nil {
			return txErr
		}

		return nil
	})
	if err != nil {
		lib.UnRedisLock(lockStr)
		response.Error(ctx, err)
		return
	}
	lib.UnRedisLock(lockStr)
	response.OkData(ctx, "success")
}

// OtcInfoUpdateFile otc上传凭证
// @Summary		otc上传凭证
// @Description	otc上传凭证
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/otc-order-detail-update/{id} [POST]
func (handler *AccountHandler) OtcInfoUpdateFile(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	id := ctx.Param("id")
	if id == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}

	var reqData model.OtcGetInfoUploadFile
	if err = ctx.ShouldBindJSON(&reqData); err != nil {
		response.Error(ctx, sferrors.NewString("请输入正确的数据"))
		return
	}
	if reqData.File == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}

	nowTime := time.Now().Format("1504")
	IntNow, _ := strconv.Atoi(nowTime)
	if IntNow < 1000 || IntNow > 1800 {
		response.Error(ctx, sferrors.NewStringf("接单时间为：10:00-18:00"))
		return
	}

	var order *emodel.My_otc_order
	err = db.GetDb().Where("id=? and (status=1 or status=2)", id).First(&order).Error
	if err != nil || order == nil {
		response.Error(ctx, sferrors.NewStringf("未找到订单"))
		return
	}
	//接单？
	if order.Uid != operator.Id {
		response.Error(ctx, sferrors.NewStringf("只有接单者可操作"))
		return
	}

	order.ImgTime = time.Now().Format("2006-01-02 15:04:05")
	order.Status = 2
	order.Image = reqData.File

	txErr := db.GetDb().Omit("create_time", "jd_time").Updates(&order).Error
	if txErr != nil {
		response.Error(ctx, txErr)
		return
	}

	response.OkData(ctx, "success")
}

// OtcInfoFangXing 放行
// @Summary		放行
// @Description	放行
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/otc-order-detail-fx/{id} [POST]
func (handler *AccountHandler) OtcInfoFangXing(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	id := ctx.Param("id")
	if id == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}

	var order *emodel.My_otc_order
	err = db.GetDb().Where("id=? and status=2", id).First(&order).Error
	if err != nil || order == nil {
		response.Error(ctx, sferrors.NewStringf("未找到订单"))
		return
	}
	//接单？
	if order.Uid == operator.Id {
		response.Error(ctx, sferrors.NewStringf("只有接单者可放行"))
		return
	}

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		var user emodel.My_user
		txErr := db.GetDb().Where("id=?", order.Uid).First(&user).Error
		if txErr != nil {
			return txErr
		}
		num := strconv.Itoa(order.Num)
		txErr = service.CreateUserLog(tx, user, float64(order.Num+10), 17, 0, "交易订单完成："+num)
		if txErr != nil {
			return txErr
		}

		txErr = service.CreateUserPointLog(tx, user, float64(order.Num*100), 33, 0, "交易订单完成："+num)
		if txErr != nil {
			return txErr
		}

		order.WcTime = time.Now().Format("2006-01-02 15:04:05")
		order.Status = 3
		txErr = tx.Omit("create_time", "jd_time", "img_time").Updates(&order).Error
		if txErr != nil {
			return txErr
		}

		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData(ctx, "success")
}

// OtcInfoFangXingDel 取消
// @Summary		取消
// @Description	取消
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/otc-order-detail/delete/{id} [POST]
func (handler *AccountHandler) OtcInfoFangXingDel(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	id := ctx.Param("id")
	if id == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}

	var order *emodel.My_otc_order
	err = db.GetDb().Where("id=? and status=0 and uid=?", id, operator.Id).First(&order).Error
	if err != nil || order == nil {
		response.Error(ctx, sferrors.NewStringf("未找到订单"))
		return
	}
	mmm := order.CreateTime[:10] + " " + order.CreateTime[11:19]
	loc, _ := time.LoadLocation("Asia/Shanghai")
	ssm, _ := time.ParseInLocation("2006-01-02 15:04:05", mmm, loc)
	ccc := ssm.Unix()

	if ccc+86400 > time.Now().Unix() {
		response.Error(ctx, sferrors.NewStringf("发布后24小时才能取消"))
		return
	}

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {
		num := strconv.Itoa(order.Num)
		txErr := service.CreateUserLog(tx, operator.My_user, 10, 18, 0, "交易订单取消："+num)
		if txErr != nil {
			return txErr
		}
		order.WcTime = time.Now().Format("2006-01-02 15:04:05")
		order.QxTime = time.Now().Format("2006-01-02 15:04:05")
		order.Status = 4
		txErr = db.GetDb().Omit("create_time", "jd_time", "img_time").Updates(&order).Error
		if txErr != nil {
			return txErr
		}
		return nil
	})

	if err != nil {
		response.Error(ctx, err)
		return
	}

	response.OkData(ctx, "success")
}

// OtcInfoTouFang 投放
// @Summary		投放
// @Description	投放
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/otc-order-detail-l/{id}/{num} [POST]
func (handler *AccountHandler) OtcInfoTouFang(ctx *gin.Context) {
	response.Error(ctx, sferrors.NewStringf("暂未开启"))
	return
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	id := ctx.Param("id")
	if id == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}

	num := ctx.Param("num")
	if num == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}

	numInt, err := strconv.Atoi(num)
	if err != nil {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}

	if numInt < 1 {
		response.Error(ctx, sferrors.NewStringf("最少1个"))
		return
	}
	if float64(numInt) > operator.Point {
		response.Error(ctx, sferrors.NewStringf("贡献积分不足"))
		return
	}

	var order *emodel.My_otc_order
	err = db.GetDb().Where("id=? and status=0", id).First(&order).Error
	if err != nil || order == nil {
		response.Error(ctx, sferrors.NewStringf("未找到订单"))
		return
	}

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		txErr := service.CreateUserPointLog(tx, operator.My_user, float64(numInt), 31, 0, "投放优先排单："+num)
		if txErr != nil {
			return txErr
		}

		txErr = tx.Exec("update my_otc_order set score=score+? where id=? ", numInt, id).Error
		if txErr != nil {
			return txErr
		}
		return nil
	})

	if err != nil {
		response.Error(ctx, err)
		return
	}

	response.OkData(ctx, "success")
}

// GetJiHuosNow 获取申请的订单
// @Summary		获取申请的订单
// @Description	获取申请的订单
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/user-jihuo-now [GET]
func (handler *AccountHandler) GetJiHuosNow(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	types := ctx.Query("type")

	logList, logListErr := service.GetJihuosNow(ctx, operator.Id, types)
	if logListErr != nil {
		response.Error(ctx, logListErr)
		return
	}
	response.OkData(ctx, logList)
}

// GetJiHuosNowDuihuan 获取申请的订单
// @Summary		获取申请的订单
// @Description	获取申请的订单
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/user-jihuo-duihuan [GET]
func (handler *AccountHandler) GetJiHuosNowDuihuan(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	logList, logListErr := service.GetDuihuanNow(ctx, operator.Id)
	if logListErr != nil {
		response.Error(ctx, logListErr)
		return
	}
	response.OkData(ctx, logList)
}

// GetKefu 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/user-level [GET]
func (handler *AccountHandler) GetKefu(ctx *gin.Context) {

	var logList []emodel.My_kf1
	db.GetDb().Model(&emodel.My_kf1{}).Find(&logList)

	response.OkData(ctx, logList)
}

// GetChildNow 获取申请的订单
// @Summary		获取申请的订单
// @Description	获取申请的订单
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/user-child-now [GET]
func (handler *AccountHandler) GetChildNow(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	types := ctx.Query("type")

	logList, logListErr := service.GetChildNow(ctx, operator.Id, types)
	if logListErr != nil {
		response.Error(ctx, logListErr)
		return
	}
	response.OkData(ctx, logList)
}

// GetUnlockLogs 获取解锁记录
// @Summary		获取解锁记录
// @Description	获取解锁记录
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/unlock-logs [GET]
func (handler *AccountHandler) GetUnlockLogs(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	logList, logListErr := service.GetUserUnlock(ctx, operator.Id)
	if logListErr != nil {
		response.Error(ctx, logListErr)
		return
	}

	response.OkData[*dto.PaginationList[emodel.My_order_w]](ctx, logList)
}

// GetTzExtract 获取解锁记录
// @Summary		获取解锁记录
// @Description	获取解锁记录
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/tz-extract [GET]
func (handler *AccountHandler) GetTzExtract(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	logList, logListErr := service.GetTzExtract(ctx, operator.Id)
	if logListErr != nil {
		response.Error(ctx, logListErr)
		return
	}

	response.OkData(ctx, logList)
}

// PutUnlockLogs 获取解锁记录
// @Summary		获取解锁记录
// @Description	获取解锁记录
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/unlock-logs/{id} [GET]
func (handler *AccountHandler) PutUnlockLogs(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	id := ctx.Param("id")
	if id == "" {
		response.Error(ctx, sferrors.NewStringf("最少10个通用积分"))
		return
	}
	var ssss emodel.My_order_w
	if err = db.GetDb().Where("id=? and uid=?", id, operator.Id).First(&ssss).Error; err != nil {
		response.Error(ctx, err)
		return
	}
	if ssss.Id <= 0 {
		response.Error(ctx, sferrors.NewStringf("非法操作"))
		return
	}
	if ssss.Status != 4 {
		response.Error(ctx, sferrors.NewStringf("只有待确认订单才能确认"))
		return
	}

	end_Time := sf_time.AddWorkdaysTimestamp(time.Now().Unix(), ssss.Days, false)

	db.GetDb().Table("my_order_w").Where("id=? and uid=?", id, operator.Id).UpdateColumns(map[string]interface{}{
		"status":   0,
		"end_time": end_Time,
		"qr_time":  time.Now().Format("2006-01-02 15:04:05"),
	})

	response.OkData(ctx, "操作成功")
}

func jsiuan(money float64, createTime *time.Time, nowTime int32) string {
	addTime := 0
	//如何计算工作日？
	switch money {
	case 10:
		addTime = 5
	case 100:
		addTime = 5
	case 500:
		addTime = 5
	}
	sf_time.AddWorkdaysTimestamp(createTime.Unix(), addTime, false)

	return ""
}

// JoinGame 兑换激活码
// @Summary		兑换激活码
// @Description	兑换激活码
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/join-game [post]
func (handler *AccountHandler) JoinGame(ctx *gin.Context) {
	operator, _, err := getCmsCtxValue(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	type DecBalanceReq struct {
		CoinType     string  `json:"coinType"`
		GameName     string  `json:"gameName"`
		ChangePoints float64 `json:"changePoints"`
		BatchNo      int     `json:"batch_no"`
	}

	var loginRequest DecBalanceReq
	err = ctx.ShouldBindJSON(&loginRequest)
	if err != nil {
		log.Errorf("参数解析失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.InvalidParameter))
		return
	}

	num := 1
	//var cnt int64
	days := time.Now().Format("20060102")
	//if err = db.GetDb().Model(&emodel.My_jihuo{}).
	//	Where("c=1 and uid=? and days=?", numStr, operator.Id, days).
	//	Count(&cnt).Error; err != nil {
	//	response.Error(ctx, err)
	//	return
	//}
	//
	//if cnt > 25 {
	//	response.Error(ctx, sferrors.NewStringf("一人一个月最多50个"))
	//}

	reqMap := make([]*emodel.My_jihuo, 0, num)

	var req emodel.My_jihuo
	req.Pid = operator.Id
	req.Bz = strconv.Itoa(int(operator.Id))
	req.Old = 1
	req.C = 1
	req.Days = days
	req.Pmobile = operator.Mobile
	req.Str = service.RandomString(12)
	req.CreateTime = time.Now().Format("2006-01-02 15:04:05")
	reqMap = append(reqMap, &req)

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		var myUser emodel.My_user
		txErr := tx.Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}
		if myUser.Money < 5 {
			return sferrors.NewStringf("余额不足")
		}

		if err = tx.Debug().Omit("update_time").Create(&reqMap).Error; err != nil {
			return err
		}
		err = service.CreateUserLog(tx, myUser, 5, 42, 0, fmt.Sprintf("兑换超级激活码（%d）个", num))
		if err != nil {
			return err
		}

		s, _ := cache.RedisContextGet[int](ctx, "duihuan")

		cache.RedisContextSet(ctx, "duihuan", *s+5, 0)

		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData(ctx, req.Str)
}
